[原创]java WEB学习笔记49:文件上传基础,基于表单的文件上传,使用fileuoload 组件
本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用
内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系。
本人互联网技术爱好者,互联网技术发烧友
微博:伊直都在0221
QQ:951226918
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1.基于表单的文件上传
1)如果在表单中使用表单元素 <input type=“file” />,浏览器在解析表单时,会自动生成一个输入框和一个按钮,输入框可供用户填写本地文件的文件名和路径名,按钮可以让浏览器打开一个文件选择框供用户选择文件:
2)Enctype 属性
① 当表单需要上传文件时,需指定表单 enctype 的值为 multipart/form-data
② 在 form 元素的语法中,enctype 属性指定将数据发送到服务器时浏览器使用的编码类型
③ enctype 属性取值:
> application/x-www-form-urlencoded:表单 enctype 属性的默认值。这种编码方案使用有限的字符集,当使用了非字母和数字时,必须用”%HH”代替(H 代表十六进制数字)。对于大容量的二进制数据或包含非 ASCII 字符的文本来说,这种编码不能满足要求
> multipart/form-data:form 设定了enctype=“multipart/form-data”属性后,表示表单以二进制传输数据
3)总结:进行文件上传时,表单需要做的准备
① 请求请求方式为 post :<form action="uploadServlet" method="post" ....... >
② 使用file 表单域 File:<input type="file" name="file"/>
③ 使用请求编码方式 : enctype="multipart/form-data"
④ 在服务端不能再使用 request.getParameter() 等方式获取请求信息。获取不到,因为请求的编码方式已经为multipart/form-data ,以二进制的方式来提交请求信息,可以使用输入流的方式来获取请求信息
upload.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>Insert title here</title>
8 </head>
9 <body>
10
11 <form action="uploadServlet" method="post" enctype="multipart/form-data">
12 File:<input type="file" name="file"/>
13 <br><br>
14 Desc:<input type="text" name="desc"/>
15 <br><br>
16 <input type="submit" value="submit"/>
17 </form>
18
19 </body>
20 </html>
UploadServlet.java
1 package com.jason.fileupload;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.InputStreamReader;
7 import java.io.Reader;
8
9 import javax.servlet.ServletException;
10 import javax.servlet.annotation.WebServlet;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14
15 /**
16 * Servlet implementation class UploadServlet
17 */
18 @WebServlet("/uploadServlet")
19 public class UploadServlet extends HttpServlet {
20 private static final long serialVersionUID = 1L;
21
22 /**
23 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
24 */
25 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
26 //1.获取请求信息
27 // String file = request.getParameter("file");
28 // String desc = request.getParameter("desc");
29 //
30 // System.out.println(file);
31 // System.out.println(desc);
32
33 //以流的方式处理 上传的代码
34 InputStream in = request.getInputStream();
35
36 Reader reader = new InputStreamReader(in);
37 BufferedReader bufferedReader = new BufferedReader(reader);
38
39 String str = null;
40
41 while((str = bufferedReader.readLine()) != null){
42 System.out.println(str);
43 }
44
45 }
46
47
48
49
50 }
2.使用fileuoload 组件
1)环境的搭建:加入jar包到 lib目录
2)基本思想:
① commons-fileupload 可以解析请求,得到一个FileItem 对象组成的List
② commons-fileupload 把请求的信息都解析为FileItem 对象,无论是一个一般的文本域还是一个文件域
③ 可以调用 FileItem 的 isFormField() 方法来判断是一个表单域 或不是表单域(则是一个文件域)
④ 进一步获取信息
1 // Process a regular form field
2 if (item.isFormField()) {
3 String name = item.getFieldName();
4 String value = item.getString();
5 ...
6 }
1 // Process a file upload
2 if (!item.isFormField()) {
3 String fieldName = item.getFieldName();
4 String fileName = item.getName();
5 String contentType = item.getContentType();
6 boolean isInMemory = item.isInMemory();
7 long sizeInBytes = item.getSize();
8 ...
9 }
3) 如何得到List<FileItem> 对象
简单方式:
1 // Create a factory for disk-based file items
2 FileItemFactory factory = new DiskFileItemFactory();
3
4 // Create a new file upload handler
5 ServletFileUpload upload = new ServletFileUpload(factory);
6
7 // Parse the request
8 List /* FileItem */ items = upload.parseRequest(request);
复杂方式:可以对文件的上床加入限制条件和其他属性
1 // Create a factory for disk-based file items
2 DiskFileItemFactory factory = new DiskFileItemFactory();
3
4 // Set factory constraints
5 factory.setSizeThreshold(yourMaxMemorySize);//设置内存中最多可以存放的上传的文件的大小,若超出则把文件写到一个临时文件夹中,以 byte 为单位
6 factory.setRepository(yourTempDirectory);//设置那个临时文件夹
7
8 // Create a new file upload handler
9 ServletFileUpload upload = new ServletFileUpload(factory);
10
11 // Set overall request size constraint
12 upload.setSizeMax(yourMaxRequestSize);//设置整个文件的大小
13
14 // Parse the request
15 List /* FileItem */ items = upload.parseRequest(request);
helloword.java测试
1 package com.jason.fileupload;
2
3 import java.io.BufferedReader;
4 import java.io.File;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.InputStreamReader;
9 import java.io.OutputStream;
10 import java.io.Reader;
11 import java.util.List;
12
13 import javax.servlet.ServletException;
14 import javax.servlet.annotation.WebServlet;
15 import javax.servlet.http.HttpServlet;
16 import javax.servlet.http.HttpServletRequest;
17 import javax.servlet.http.HttpServletResponse;
18
19 import org.apache.commons.fileupload.FileItem;
20 import org.apache.commons.fileupload.FileUploadException;
21 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
22 import org.apache.commons.fileupload.servlet.ServletFileUpload;
23
24 /**
25 * Servlet implementation class UploadServlet
26 */
27 @WebServlet("/upload/uploadServlet")
28 public class UploadServlet extends HttpServlet {
29 private static final long serialVersionUID = 1L;
30
31 /**
32 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
33 * response)
34 */
35 protected void doPost(HttpServletRequest request,
36 HttpServletResponse response) throws ServletException, IOException {
37 // 1.得到FileIrem 的集合 items
38 // Create a factory for disk-based file items
39 DiskFileItemFactory factory = new DiskFileItemFactory();
40
41 // Set factory constraints
42 factory.setSizeThreshold(1024 * 500);
43 File tempDirectory = new File("e:\\tempDirectory");
44 factory.setRepository(tempDirectory);
45
46 // Create a new file upload handler
47 ServletFileUpload upload = new ServletFileUpload(factory);
48
49 // Set overall request size constraint
50 upload.setSizeMax(1024 * 1024 * 5);
51
52 // Parse the request
53 try {
54 List<FileItem> items = upload.parseRequest(request);
55 // 2.遍历items:若是一般表单域,打印信息
56 for (FileItem item : items) {
57 if (item.isFormField()) {
58 String name = item.getFieldName();
59 String value = item.getString();
60 System.out.println(name + " : " + value);
61 } else {
62 // 3.若是文件域则把文件保存到目录 files
63 String fieldName = item.getFieldName();
64 String fileName = item.getName();
65 String contentType = item.getContentType();
66 long sizeInBytes = item.getSize();
67
68 System.out.println(fieldName);
69 System.out.println(fileName);
70 System.out.println(contentType);
71 System.out.println(sizeInBytes);
72
73 InputStream in = item.getInputStream();
74 byte[] buffer = new byte[1024];
75 int len = 0;
76 fileName = "e:\\file\\" + fileName;
77 System.out.println(fileName);
78
79 OutputStream out = new FileOutputStream(fileName);
80 while ((len = in.read(buffer)) != -1) {
81 out.write(buffer, 0, len);
82 }
83 out.close();
84 in.close();
85 }
86 }
87
88 } catch (FileUploadException e) {
89 e.printStackTrace();
90 }
91
92 }
93
94 }
upload.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>Insert title here</title>
8 </head>
9 <body>
10
11 <form action="uploadServlet" method="post" enctype="multipart/form-data">
12 File:<input type="file" name="file"/>
13 <br><br>
14 Desc:<input type="text" name="desc"/>
15 <br><br>
16 <input type="submit" value="submit"/>
17 </form>
18
19 </body>
20 </html>