`
jym1340056078
  • 浏览: 2549 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

文件上传 监听

 
阅读更多

一、文件上传
1、前提条件:
form表单提供input type="file"类型的输入域,必须有name属性
form表单的enctype属性取值为multipart/form-data
form表单的method提交方式为post方式
2、如果表单的enctype设置成了multipart/form-data,那么传统获取参数的方式就失效了。

3、上传文件的请求正文内容如下:
-----------------------------7dc22234707de
Content-Disposition: form-data; name="username"

wzt

-----------------------------7dc22234707de
Content-Disposition: form-data; name="photo1"; filename="C:\Documents and Settings\鐜嬫槶鐝絓妗岄潰\a.txt"

Content-Type: text/plain

aaaaaa

-----------------------------7dc22234707de
Content-Disposition: form-data; name="photo2"; filename="C:\Documents and Settings\鐜嬫槶鐝絓妗岄潰\b.txt"
Content-Type: text/plain
bbbbbb
-----------------------------7dc22234707de--

按照MIME协议进行描述的。

二、利用apache-commons-fileupload组件进行文件上传
1、所需jar包
commons-fileupload.jar
commons-io.jar
2、核心类
DiskFileItemFacotry:创建FileItem的工厂。
还能设置缓存大小(默认10k)和临时文件的存放路径
ServletFileUpload:解析请求的正文,得到代表表单某一部分的FileItem对象
FileItem:代表表单中的一个输入域
boolean isFormField():是否是普通表单数据
String getFieldName():得到普通输入域的名称
String getString():得到普通输入域提交的数据值
InputStream getInputStream():得到上传域的输入流
String getName():得到上传文件的名称

三、文件上传时需要考虑的9大问题
1、上传文件名的中文乱码和表单数据的中文乱码(传统的设置编码无效)
普通字段中文数据
FileItem.getString(编码)
上传文件名中文乱码:
方式一:request.setCharacterEncoding("UTF-8")
方式二:ServletFileUpload.setHeaderEncoding("UTF-8");

2、如何保证服务器的安全
把上传的文件放到用户访问不到的地方WEB-INF

3、多次上传同名文件的覆盖
UUID更改文件名,保证不重复
UUID_文件名
当前的毫秒值:(乐观者)

4、如何防止同一目录下文件太多的问题
分目录存储

hashcode算目录
1100 0011 1101 1100 0101 0001 1010 1101
0000 0000 0000 0000 0000 0000 0000 1111
0000 0000 0000 0000 0000 0000 0000 1101  0~15
1100 0011 1101 1100 0101 0001 1010 1101
0000 0000 0000 0000 0000 0000 1111 0000
0000 0000 0000 0000 0000 0000 1010 0000>>4

0000 0000 0000 0000 0000 0000 0000 1010 0~15

 

5、上传文件的大小控制(单个文件和总大小),及如何友好提示用户
单个文件:
单个文件大小限制:
ServletFileUpload.setFileSizeMax(字节)
超出了大小:FileUploadBase.FileSizeLimitExceededException异常

总文件大小:
ServletFileUpload.setSizeMax(字节)
超出了大小:FileUploadBase.SizeLimitExceededException异常

6、超出10k的文件的临时文件的处理
会出现临时文件。组件本身不会自动删除临时文件。
在上传完毕后,执行FileItem.delete()方法手工删除。
注意:关闭流后再删除

7、限制上传文件的类型
通过判断上传文件的扩展名来进行限制(不严格)

FileItem.getContentType():获取到MIME类型,通过这个进行过滤
图片的MIME类型都是以images开头

8、监听文件的上传进度
ServletFileUpload注册监听

9、用户没有选择文件上传时的问题

示例:

 

[java] view plain copy
 
  1. package com.upload;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8. import java.text.DateFormat;  
  9. import java.text.SimpleDateFormat;  
  10. import java.util.Date;  
  11. import java.util.List;  
  12. import java.util.UUID;  
  13.   
  14. import javax.servlet.ServletException;  
  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. public class UploadServlet extends HttpServlet {  
  25.   
  26.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  27.             throws ServletException, IOException {  
  28.   
  29.         DiskFileItemFactory factory = new DiskFileItemFactory();  
  30.         ServletFileUpload upload = new ServletFileUpload(factory);  
  31.   
  32.         request.setCharacterEncoding("UTF-8");  
  33.   
  34.         String inFilePath = getServletContext().getRealPath(  
  35.                 "\\WEB-INF\\upload\\");  
  36.         String dirDate = DateFormat.getDateInstance().format(new Date());  
  37.         inFilePath = inFilePath + "\\" + dirDate;  
  38.   
  39.         File file = new File(inFilePath);  
  40.   
  41.         if (!file.exists())  
  42.             file.mkdirs();  
  43.   
  44.         try {  
  45.             List<FileItem> list = upload.parseRequest(request);  
  46.   
  47.             for (FileItem item : list) {  
  48.   
  49.                 if (item.isFormField()) {  
  50.   
  51.                     String name = item.getFieldName();  
  52.                     String value = item.getString("UTF-8");  
  53.                 } else {  
  54.   
  55.                     String fileType = item.getContentType();  
  56.                     String fileName = item.getName();  
  57.   
  58.                     fileName = fileName  
  59.                             .substring(fileName.lastIndexOf("\\") + 1);  
  60.   
  61.                     OutputStream out = new FileOutputStream(inFilePath + "\\"  
  62.                             + UUID.randomUUID().toString() + "_" + fileName);  
  63.   
  64.                     InputStream in = item.getInputStream();  
  65.                     byte[] buff = new byte[1024];  
  66.                     int len = -1;  
  67.                     while ((len = in.read(buff)) != -1) {  
  68.                         out.write(buff);  
  69.                     }  
  70.                     out.close();  
  71.                     in.close();  
  72.                 }  
  73.                 System.out.println("上传完成");  
  74.             }  
  75.   
  76.         } catch (FileUploadException e) {  
  77.             throw new RuntimeException("上传失败");  
  78.         }  
  79.     }  
  80.   
  81.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  82.             throws ServletException, IOException {  
  83.   
  84.         doGet(request, response);  
  85.     }  
  86.   
  87. }  



 

四、Servlet规范中的监听

编写步骤:
a、编写一个类,实现特定的监听接口
b、在web.xml中进行注册监听
<listener>
<listener-class>com.itheima.listener.MyServletContextListener</listener-class>
</listener>

1、(3个)监听ServletContext、HttpSession、ServletRequest三个对象的创建和销毁
ServletContextListener
HttpSessionListener
ServletRequestListener

2、(3个)监听域对象中属性的增加和删除的事件监听器
ServletContextAttributeListener
HttpSessionAttributeListener
ServletRequestAttributeListener

3、(2)感知型监听器。(不需要注册)
HttpSessionBindingListener:感知自己被绑到了HttpSession域中了
HttpSessionActivationListener:感知自己激活和钝化

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics