Servlet实现文件上传

WEB上传采用POST方式,form中设置enctype属性为 multipart/form-data ----> 指定浏览器使用二进制进行上传 

          默认为:application/x-www-form-unclearded --->使用ASCII向服务器发送数据

因为上传文件是采用二进制方式发送,所以servlet中就不能通过HttpServletRequest对象的getParameter方法来获取了,需要按照HTTP协议规定的格式对浏览器提交的request进行解析。

 1 import java.io.*;
 2 import java.util.*;
 3 import javax.servlet.ServletException;
 4 import javax.servlet.http.HttpServlet;
 5 import javax.servlet.http.HttpServletRequest;
 6 import javax.servlet.http.HttpServletResponse;
 7 import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
 8 import org.apache.tomcat.util.http.fileupload.FileItem;
 9 import org.apache.tomcat.util.http.fileupload.FileUploadException;
10 
11 public class UpServlet extends HttpServlet {
12 
13     @Override
14     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
15             throws ServletException, IOException {
16         doPost(req, resp);
17     }
18 
19     @Override
20     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
21             throws ServletException, IOException {
22         File file1 = null; 
23         File file2 = null;
24         String description1 = null, description2 = null;
25         PrintWriter out = resp.getWriter();
26         DiskFileUpload diskFileUpload = new DiskFileUpload();        //用于解释request,因为form中的 enctype属性设置为multipart/form-data指定浏览器通过二进制上传
27         
28         try{
29             List<FileItem> list = diskFileUpload.parseRequest(req);        //将获取的结果集放入到一个list
30             out.println("Traverse all of the FileItem...<br/>");
31             for(FileItem fileItem : list) {                                //增强的for循环遍历所有FileItem
32                 if(fileItem.isFormField()) {                            //判断是否为文本域
33                     if("desription1".equals(fileItem.getFieldName())) {        //判断是否为该参数
34                         out.println("<遍历>Traversal to desciption1 ... <br/>");
35                         description1 = new String(fileItem.getString().getBytes(), "ISO-8859-1");
36                     }
37                     if("description2".equals(fileItem.getFieldName())) {
38                         out.println("<遍历>Traversal to description2 ...<br/>");
39                         description2 = new String(fileItem.getString().getBytes(), "ISO-8859-1");
40                     }
41                 } else {
42                     if("file1".equals(fileItem.getFieldName())) {
43                         File remoteFile = new File(new String(fileItem.getName().getBytes(), "ISO-8895-1"));
44                         out.println("<遍历>Traversal to file1 ...<br/>");
45                         out.println("Client File Location: " + remoteFile.getAbsolutePath() + "<br/>");
46                         
47                         //服务器端文件放在upload下
48                         file1 = new File(this.getServletContext().getRealPath("attachment"), remoteFile.getName());
49                         file1.getParentFile().mkdirs();                 //创建一个文件夹路径
50                         file1.createNewFile();                            //创建一个新的文件
51                         
52                         InputStream is = fileItem.getInputStream();            //将fileItem中的内容输出到文件中
53                         
54                         OutputStream os = new FileOutputStream(file1);
55                         
56                         try{
57                             byte[] buffer = new byte[1024];                //建立一个缓冲区
58                             int len = 0;                                //设定实际缓存的长度
59                             while((len=is.read(buffer)) > -1) {            //读入缓存
60                                 os.write(buffer, 0 ,len);
61                             }
62                             out.println("Save the file has been " + file1.getAbsolutePath() + "<br/>");
63                         } finally {
64                             is.close();
65                         }
66                         if("file2".equals(fileItem.getFieldName())) {
67                             
68                         }
69                     }
70                 }
71             }
72             out.println("Request Analysis completed");
73         } catch(FileUploadException e) {
74         }
75     }
76 
77 }
原文地址:https://www.cnblogs.com/CodeMaker/p/Upload.html