在学习Servlet过程中,针对图片上传做了一个Demo,实现的功能是:在a页面上传图片,点击提交后,将图片保存到服务器指定路径(D:/image);跳转到b页面,b页面读取展示绝对路径(D:/image)的图片。主要步骤如下:
步骤一:上传页面uploadphoto.jsp
需要注意两个问题:
1.form 的method必须是post的,get不能上传文件, 还需要加上enctype="multipart/form-data" 表示提交的数据是二进制文件。
2.需要提供type="file" 的字段进行上传
1
|
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<%@ page language= "java" contentType= "text/html; charset=UTF-8"
pageEncoding= "UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" " http://www.w3.org/TR/html4/loose.dtd " >
<html>
<head>
<meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" >
<title>upload page</title>
</head>
<body >
<form action= "uploadPhoto" method= "post" enctype= "multipart/form-data" >
英雄名称: <input type= "text" name= "heroName" /> <br><br>
上传头像: <input type= "file" name= "filepath" /> <br><br>
<input type= "submit" value= "上传" >
</form>
</body>
</html>
|
步骤二:UploadPhotoServlet类
1. 需要用到两个第三方的jar包,commons-io-1.4.jar和commons-fileupload-1.2.2.jar。项目是Maven项目,直接在pom.xml文件中引入:
1
|
2
3
4
5
6
7
8
9
10
|
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version> 2.4 </version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version> 1.3 . 1 </version>
</dependency>
|
2. 前部分代码是固定写法,用来做一些准备工作。 直到遍历出Item,一个Item就是对应一个浏览器提交的数据,通过item.getInputStream可以打开浏览器上传的文件的输入流。
3. 客户提交的文件名有可能是一样的,所以在服务端保存文件的时候,不能使用客户提交的文件名。这里使用的是一种粗糙的解决文件名重复的办法,即使用时间戳。
1
|
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
package servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadPhotoServlet extends HttpServlet {
public static String filename = null ;
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,HttpServletResponse response){
}
@SuppressWarnings ( "rawtypes" )
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
factory.setSizeThreshold( 1024 * 1024 );
List items = null ;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator iter = items.iterator();
while (iter.hasNext()){
FileItem item = (FileItem) iter.next();
if (!item.isFormField()){
// 根据时间戳创建头像文件
filename = System.currentTimeMillis() + ".jpg" ;
System.out.println(request.getContextPath());
/*File f = new File(getServletContext().getRealPath("upload"));*/
File f = new File( " D://image " );
if (!f.exists()) {
f.mkdir();
}
String imgsrc = f + "/" + filename;
// 复制文件
InputStream is = item.getInputStream();
FileOutputStream fos = new FileOutputStream(imgsrc);
byte b[] = new byte [ 1024 * 1024 ];
int length = 0 ;
while (- 1 != (length = is.read(b))) {
fos.write(b, 0 , length);
}
fos.flush();
fos.close();
} else {
System.out.println(item.getFieldName());
String value = item.getString();
value = new String(value.getBytes( "ISO-8859-1" ), "UTF-8" );
System.out.println(value);
}
}
//request.setAttribute("filename", filename);
//request.getRequestDispatcher("/showPhoto").forward(request, response);
response.sendRedirect( "/ServletTest/showPhoto?filename=" +filename);
}
}
|
步骤三:ShowPhotoServlet类
其实这个类可以省略,即可以直接在UploadPhotoServlet类中跳转到页面showphoto.jsp,但是为了学习Servlet跳转方面的知识,于是增加一个新的Servlet类。
1
|
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ShowPhotoServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
String filename = request.getParameter( "filename" ).toString();
response.sendRedirect( "/ServletTest/showphoto.jsp?filename=" +filename);
}
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
String filename = request.getAttribute( "filename" ).toString();
request.setAttribute( "filename" , filename);
request.getRequestDispatcher( "/showphoto.jsp" ).forward(request, response);
}
}
|
1.servlet跳转至jsp(注意)
详见:http://www.zzvips.com/article/120301.htm
a.服务端跳转浏览器的地址不变(请求转发)
1
|
2
|
request.setAttribute( "filename" , filename);
request.getRequestDispatcher( "/showphoto.jsp" ).forward(request, response);
|
b.客户端跳转浏览器的地址发生变化(请求重定向)
1
|
|
response.sendRedirect( "/ServletTest/showphoto.jsp?filename=" +filename);
|
2.servlet跳转至另一个servlet
a.服务端跳转需要重写doPost以获取传递参数
1
|
|
String filename = request.getAttribute( "filename" ).toString();
|
b.客户端跳转需要重写doGet以获取传递参数
1
|
|
String filename = request.getParameter( "filename" ).toString();
|
步骤三:web.xml配置
1
|
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<servlet>
<servlet-name>UploadPhotoServlet</servlet-name>
<servlet- class >servlet.UploadPhotoServlet</servlet- class >
</servlet>
<servlet-mapping>
<servlet-name>UploadPhotoServlet</servlet-name>
<url-pattern>/uploadPhoto</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ShowPhotoServlet</servlet-name>
<servlet- class >servlet.ShowPhotoServlet</servlet- class >
</servlet>
<servlet-mapping>
<servlet-name>ShowPhotoServlet</servlet-name>
<url-pattern>/showPhoto</url-pattern>
</servlet-mapping>
|
步骤四:展示页面showphoto.jsp
1
|
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<%@ page language= "java" contentType= "text/html; charset=UTF-8"
pageEncoding= "UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" " http://www.w3.org/TR/html4/loose.dtd " >
<html>
<head>
<meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" >
<title>Image page</title>
</head>
<body>
<%
String filename = request.getParameter( "filename" );
String srcimg = "/image/" +filename;
%>
<img src= "<%=srcimg%>" />
</body>
</html>
|
1.配置虚拟路径
图片和工程不在一个盘符下。图片也不能放到工程下。 在JSP 文件中 <img src="C:/Users/fx/Pictures/test.jpg"/> 这样是引不到图片的。因为,JSP页面在引图片的时候是在页面解析的路径是:<img src="http://localhost:8080/test/images/1.jpg">。也就是说JSP在引图片的时候是先去工程目录下找的。
解决办法:
使用虚拟路径来配置,在tomcat下的server.xml中增加一个代码 在<Host></Host>中间:
1
|
|
<Context docBase= "D:\image" path= "/image" reloadable= "true" />
|
然后在JSP页面中<img src = "/image/(图片名)">就可以访问图片了。
最终实现效果:
上传界面:
展示界面:
保存图片的文件夹:
总结
以上所述是小编给大家介绍的通过Java Servlet图片上传至指定文件夹并显示图片,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:http://www.cnblogs.com/Junsept/p/7279343.html