文件上传

 1 package cn.servlet;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 import java.util.List;
 6 import java.util.UUID;
 7 
 8 import javax.servlet.ServletException;
 9 import javax.servlet.annotation.WebServlet;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 
14 import org.apache.commons.fileupload.FileItem;
15 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
16 import org.apache.commons.fileupload.servlet.ServletFileUpload;
17 
18 @WebServlet(urlPatterns = "/up2")
19 public class Up2Servlet extends HttpServlet {
20     @Override
21     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
22         req.setCharacterEncoding("UTF-8");
23 
24         DiskFileItemFactory disk = new DiskFileItemFactory();
25         ServletFileUpload up = new ServletFileUpload(disk);
26         // 如果你不知道用户上传多少个文件,则应该遍历
27         try {
28             List<FileItem> list = up.parseRequest(req);
29             FileItem item1 = list.get(0);
30             String name = item1.getString("UTF-8");// 对于非文件,用于这种方式来获取用户提交的
31             FileItem item2 = list.get(1);
32             String age = item2.getString("UTF-8");
33             FileItem item3 = list.get(2);
34             String fileName = item3.getName();
35             fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
36             // 对文件重名称
37             String extName = fileName.substring(fileName.lastIndexOf(".") + 1);// abc.jpg
38                                                                                 // -=>
39                                                                                 // jpg
40             String uuid = UUID.randomUUID().toString().replace("-", "");
41             String newFileName = uuid + "." + extName;
42             // 获取文件上传的真实的目录
43             String realPath = getServletContext().getRealPath("/files");
44             // 实现文件上传
45             item3.write(new File(realPath, newFileName));
46             // 将转发到show.jsp显示
47             req.setAttribute("name", name);
48             req.setAttribute("age", age);
49             req.setAttribute("oldFileName", fileName);
50             req.setAttribute("newFileName", newFileName);
51             req.getRequestDispatcher("/jsps/show.jsp").forward(req, resp);
52         } catch (Exception e) {
53             e.printStackTrace();
54         }
55 
56     }
57 }

 

posted @ 2016-06-22 20:37  追梦人丶  阅读(160)  评论(0编辑  收藏  举报