commons.fileupload 文件上傳
阿新 • • 發佈:2017-09-26
session val sta ava 工廠 ota data 自定義 this
編輯jsp頁面獲取文件
1 <html>
2 <head>
3 <base href="<%=basePath%>">
4
5 <title>My JSP ‘upload.jsp‘ starting page</title>
6
7 <meta http-equiv="pragma" content="no-cache">
8 <meta http-equiv="cache-control" content="no-cache">
9 <meta http-equiv="expires" content="0">
10 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
11 <meta http-equiv="description" content="This is my page">
12 <!--
13 <link rel="stylesheet" type="text/css" href="styles.css">
14 -->
15
16 </head>
17
18 <body>
19 <form action="upload1" method="post" enctype="Multipart/form-data">
20 file:<input type="file" name="upload">
21 <input type="submit" value="上傳">
22 </form>
23 </body>
24 </html>
servlet上傳:
1 import java.io.File;
2 import java.io.IOException;
3 import java.io.PrintWriter;
4 import java.util.List;
5 import java.util.UUID;
6
7 import javax.servlet.ServletException;
8 import javax.servlet.annotation.MultipartConfig;
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.FileUploadException;
16 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
17 import org.apache.commons.fileupload.servlet.ServletFileUpload;
18 @WebServlet("/upload1")
19
20 public class Upload1 extends HttpServlet {
21
22 public void doGet(HttpServletRequest request, HttpServletResponse response)
23 throws ServletException, IOException {
24 doPost(request, response);
25 }
26
27 public void doPost(HttpServletRequest request, HttpServletResponse response)
28 throws ServletException, IOException {
29 /**
30 * 1、創建文件項工廠
31 */
32
33 DiskFileItemFactory factory = new DiskFileItemFactory();
34 /**
35 * 2、創建解析請求 數據的ServletFileUpload對象
36 */
37 ServletFileUpload upload = new ServletFileUpload(factory);
38 try {
39 /**
40 * 3、解析請求數據 返回FileItem 列表
41 */
42 List<FileItem> list = upload.parseRequest(request);
43 /**
44 * 4、解析獲取每一個FileItem 對象
45 */
46
47 FileItem item = list.get(0);
48
49 //驗證當前FileItem 是否是表單字段 如果fales 則取到的是文件
50 item.isFormField();
51 /**
52 * 5、文件名及路徑處理
53 */
54 //處理文件
55 String filename= item.getName();
56 //截取文件擴展名
57 String extName = filename.substring(filename.lastIndexOf("."));
58 //生成UUID作為文件名
59 String newName= UUID.randomUUID().toString();
60 //獲取服務器上自定義的存放文件的目錄
61 String rootPath = request.getSession().getServletContext().getRealPath("/upload");
62 //生成完整的文件路徑
63 String newPath = rootPath+"/"+newName+extName;
64 System.out.println(newPath);
65 /**
66 * 6、文件寫入
67 */
68 item.write(new File(newPath));
69
70 } catch (FileUploadException e) {
71 e.printStackTrace();
72 } catch (Exception e) {
73 e.printStackTrace();
74 }
75 }
76
77 }
commons.fileupload 文件上傳