本文实例为大家分享了Servlet文件上传的具体代码,供大家参考,具体内容如下
两点要素:
1.表单提交方式必须是post
2.enctype一定要是multipart/form-data。
enctype的默认值是application/x-www-form-urlencoded,
这种编码格式只支持键值对的数据,?键=值&键=值,只能是字符串,无法传输文件。
multipart/form-data这种编码可以上传文件
需要的jar包:
实现:
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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 UploadServlet extends HttpServlet {
//文件夹路径常量
private static String TEMP_PATH = "E:/Learning/temp/170926" ;
private static final long serialVersionUID = 3364746345428715093L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
PrintWriter out = response.getWriter();
// 接收文件
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// 判断是否是文件上传请求
if (!isMultipart) {
out.println( "Error : 表单必须包含 enctype=multipart/form-data" );
return ;
}
// 用于创建解析文件上传的工厂类
DiskFileItemFactory factory = new DiskFileItemFactory();
// 用于从请求中解析出文件
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// 获取所有提交过来的文件(包含表单内容) 这个FileItem叫做一个项,这个项有可能是文件也有可能是表单参数
List<FileItem> items = upload.parseRequest(request);
// 定义一个输出流
FileOutputStream fos = null ;
//缓冲区
byte [] buf = new byte [ 8192 ];
if (items != null && items.size() > 0 ) { // 不为空且长度大于0则遍历之
for (FileItem item : items) {
if (item.isFormField()) { // isFormField = true 文本框的值
out.println( "用户名: " + item.getString() + "<br />" );
} else {
//获取输入流
BufferedInputStream bis = new BufferedInputStream(item.getInputStream());
//初始化本地输出流
fos = new FileOutputStream( new File(TEMP_PATH + "/" + item.getName()));
int len = - 1 ;
while ((len = bis.read(buf)) != - 1 ) {
fos.write(buf , 0 , len);
fos.flush();
}
out.println( "文件: " + item.getName() + "已上传 <br />" );
}
}
}
} catch (FileUploadException e) {
out.println( "Error: 文件解析异常" );
}
}
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://blog.csdn.net/qq_36311372/article/details/78388394