java servlet中上传文件的简单实现(基于第三方jar)

这里的案例使用了两种文件上传的组件、分别介绍

1、使用JSPSmartUpload完成上传

 1 package test_servlet_package;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 import java.util.Calendar;
 6 import java.util.Random;
 7 import javax.servlet.ServletException;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 import com.jspsmart.upload.SmartUpload;
12 
13 public class test_servlet_SmartUpload extends HttpServlet {
14 
15     String tempPath = "D:\\test";
16     String filePath = "D:\\filePath";
17     @Override
18     protected void doPost(HttpServletRequest request, HttpServletResponse response)
19             throws ServletException, IOException {
20         response.setCharacterEncoding("GBK");
21         SmartUpload mySmartUpload = new SmartUpload();
22         // 初始化
23         mySmartUpload.initialize(getServletConfig(), request, response);
24         long file_size_max = 4000000;
25         String ext = "";
26         try {
27             mySmartUpload.setAllowedFilesList("jpg,gif,png");
28             mySmartUpload.upload();// 上载文件
29         } catch (Exception e) {
30             response.getWriter().write("<script> alert('只允许上传.jpg和.gif类型图片文件');</script>");
31         }
32         try {
33             com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
34             if (!myFile.isMissing()) {
35                 ext = myFile.getFileExt(); // 取得后缀名
36                 int file_size = myFile.getSize(); // 取得文件的大小
37                 String saveurl = "";
38                 if (file_size < file_size_max) {
39                     // 更改文件名,取得当前上传时间的毫秒数值
40                     Calendar calendar = Calendar.getInstance();
41                     String filename = String.valueOf(calendar.getTimeInMillis());
42                     Random r = new Random();
43                     String ram = String.valueOf(r.nextInt(1241241241));
44                     filename = filename + ram;
45                     filename = filename.substring(0, (filename.length() - ext.length() - 1));
46                     //saveurl = this.getServletContext().getRealPath("/") + "/uploadFile/" + filename + "." + ext;
47                     //System.out.println(saveurl);
48                     File uploadFile2 = new File(filePath);
49                     if(!uploadFile2.exists()){
50                         uploadFile2.mkdirs();
51                     }
52                     myFile.saveAs(filePath+"/"+filename+"." + ext);
53                 }
54             }
55             String name = mySmartUpload.getRequest().getParameter("name");
56             request.setAttribute("name", "name");
57             request.getSession().setAttribute("name", "name");
58             request.getSession().getId();
59             System.out.println(name);
60         } catch (Exception e) {
61             e.printStackTrace();
62         }
63         request.getRequestDispatcher("/uploadsuccess.jsp").forward(request, response);
64     }
65 }

2、使用commons-fileupload完成文件上传

 1 package test_servlet_package;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 import java.io.PrintWriter;
 6 import java.util.Iterator;
 7 import java.util.List;
 8 import javax.servlet.ServletException;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import org.apache.commons.fileupload.FileItem;
13 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
14 import org.apache.commons.fileupload.servlet.ServletFileUpload;
15 
16 public class test_servlet extends HttpServlet {
17 
18     String tempPath = "D:\\test";
19     String filePath = "D:\\filePath";
20     @Override
21     protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
22         res.setContentType("text/plain;charset=gbk");
23         PrintWriter pw = res.getWriter();
24         try {
25             DiskFileItemFactory diskFactory = new DiskFileItemFactory();
26             // threshold 极限、临界值,即硬盘缓存 1M
27             diskFactory.setSizeThreshold(4 * 1024);
28             // repository 贮藏室,即临时文件目录
29             diskFactory.setRepository(new File(tempPath));
30             ServletFileUpload upload = new ServletFileUpload(diskFactory);
31             // 设置允许上传的最大文件大小 4M
32             upload.setSizeMax(4 * 1024 * 1024);
33             // 解析HTTP请求消息头
34             List<FileItem> fileItems = upload.parseRequest(req);
35             Iterator<FileItem> iter = fileItems.iterator();
36             while (iter.hasNext()) {
37                 FileItem item = (FileItem) iter.next();
38                 if (item.isFormField()) {
39                     System.out.println("处理表单内容 ...");
40                     processFormField(item, pw);
41                 } else {
42                     System.out.println("处理上传的文件 ...");
43                     processUploadFile(item, pw);
44                 }
45             }
46             pw.close();
47         } catch (Exception e) {
48             System.out.println("使用 fileupload 包时发生异常 ...");
49             e.printStackTrace();
50         }
51     }
52 
53     // 处理表单内容
54     private void processFormField(FileItem item, PrintWriter pw) throws Exception {
55         String name = item.getFieldName();
56         String value = item.getString();
57         pw.println(name + " : " + value + "\r\n");
58     }
59 
60     // 处理上传的文件
61     private void processUploadFile(FileItem item, PrintWriter pw) throws Exception {
62         // 此时的文件名包含了完整的路径,得注意加工一下
63         String filename = item.getName();
64         System.out.println("完整的文件名:" + filename);
65         int index = filename.lastIndexOf("\\");
66         filename = filename.substring(index + 1, filename.length());
67         long fileSize = item.getSize();
68         if ("".equals(filename) && fileSize == 0) {
69             System.out.println("文件名为空 ...");
70             return;
71         }
72         File uploadFile = new File(filePath + "/" + filename);
73         File uploadFile2 = new File(filePath);
74         if(!uploadFile2.exists()){
75             uploadFile2.mkdirs();
76         }
77         item.write(uploadFile);
78         pw.println(filename + " 文件保存完毕 ...");
79         pw.println("文件大小为 :" + fileSize + "\r\n");
80     }
81 }

3、依赖的jar:

 1 <classpath>
 2     <classpathentry kind="lib" path="base/WEB-INF/lib/commons-fileupload-1.2.2.jar"/>
 3     <classpathentry kind="lib" path="base/WEB-INF/lib/commons-io-2.0.1.jar"/>
 4     <classpathentry kind="lib" path="base/WEB-INF/lib/jsmartcom_zh_CN.jar"/>
 5     <classpathentry kind="lib" path="base/WEB-INF/lib/mysql-connector-java-5.1.21-bin.jar"/>
 6     <classpathentry kind="lib" path="base/WEB-INF/lib/taglibs-standard-compat-1.2.1.jar"/>
 7     <classpathentry kind="lib" path="base/WEB-INF/lib/taglibs-standard-impl-1.2.1.jar"/>
 8     <classpathentry kind="lib" path="base/WEB-INF/lib/taglibs-standard-jstlel-1.2.1.jar"/>
 9     <classpathentry kind="lib" path="base/WEB-INF/lib/taglibs-standard-spec-1.2.1.jar"/>
10     <classpathentry kind="output" path="base/WEB-INF/classes"/>
11 </classpath>

 

posted on 2017-06-08 11:09  祥昊  阅读(1842)  评论(0编辑  收藏  举报

导航