Java web中,当表单含有文件上传时,提交数据的如何读取

来源:互联网 发布:电脑桌面软件打不开 编辑:程序博客网 时间:2024/05/16 15:08

当提交表单里包含文件上传的时候,即Form的enctype属性值为multipart/form-data时,后台是无法像普通表单那样通过request.getParameter来获取用户提交的数据的。

这时候,当然可以通过解析提交到服务器的数据流来得到数据了,但是这样不但麻烦而且容易出错。

最好的方式是使用第三方的jar包获取数据,这方面有很多现成的成熟优秀的jar包。最常用的时以下三个:

apache的commons-fileupload : http://commons.apache.org/fileupload/

O'Reilly的cos: http://www.servlets.com/cos/index.html

jspsmart的SmartUpload:官方不提供下载了,google搜吧。

其中,据评测效率最高的是COS,最慢的是SmartUpload;最常用的是common-upload;文件太大时SmartUpland会崩溃。


1. common-upload示例代码:

view plaincopy to clipboardprint?
  1. // 判断enctype属性是否为multipart/form-data   
  2. boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
  3.   
  4. // Create a factory for disk-based file items  
  5. DiskFileItemFactory factory = new DiskFileItemFactory();  
  6.   
  7. // 当上传文件太大时,因为虚拟机能使用的内存是有限的,所以此时要通过临时文件来实现上传文件的保存  
  8. // 此方法是设置是否使用临时文件的临界值(单位:字节)   
  9. factory.setSizeThreshold(yourMaxMemorySize);  
  10.   
  11. // 与上一个结合使用,设置临时文件的路径(绝对路径)   
  12. factory.setRepository(yourTempDirectory);  
  13.   
  14. // Create a new file upload handler   
  15. ServletFileUpload upload = new ServletFileUpload(factory);  
  16.   
  17. // 设置上传内容的大小限制(单位:字节)   
  18. upload.setSizeMax(yourMaxRequestSize);  
  19.   
  20. // Parse the request   
  21. List<?> items = upload.parseRequest(request);  
  22.   
  23. Iterator iter = items.iterator();  
  24. while (iter.hasNext()) {  
  25.     FileItem item = (FileItem) iter.next();  
  26.   
  27.     if (item.isFormField()) {  
  28.         //如果是普通表单字段   
  29.         String name = item.getFieldName();  
  30.             String value = item.getString();  
  31.             ...  
  32.     } else {  
  33.         //如果是文件字段   
  34.         String fieldName = item.getFieldName();  
  35.             String fileName = item.getName();  
  36.             String contentType = item.getContentType();  
  37.             boolean isInMemory = item.isInMemory();  
  38.             long sizeInBytes = item.getSize();  
  39.             ...  
  40.               
  41.             // Process a file upload  
  42.                 if (writeToFile) {  
  43.                     File uploadedFile = new File(...);  
  44.                     item.write(uploadedFile);  
  45.                 } else {  
  46.                     InputStream uploadedStream = item.getInputStream();  
  47.                     ...  
  48.                     uploadedStream.close();  
  49.                 }  
  50.     }  
  51. }  


2. cos示例代码:

view plaincopy to clipboardprint?
  1. // 设置大小限制(单位:字节)   
  2. final int permitedSize = 314572800;  
  3.   
  4. try {                 
  5.     String type = "";  
  6.     String name = "";  
  7.     String originalFilename = "";  
  8.     String extension1 = "";  
  9.     String extension2 = "";  
  10.     String filename = "";  
  11.       
  12.     //上传目录   
  13.     String strDirectory = "files";  
  14.     String uploadPath = request.getRealPath("//WEB-INF//"+strDirectory+"//");  
  15.       
  16.     // 获取句柄   
  17.     MultipartRequest multipartRequest = new MultipartRequest(request, uploadPath,   
  18.                      permitedSize, "ISO-8859-1"new DefaultFileRenamePolicy());   
  19.           
  20.     // 取得文件   
  21.     Enumeration files = multipartRequest.getFileNames();         
  22.           
  23.     // 取得文件详细信息    
  24.     while (files.hasMoreElements()) {   
  25.            name = (String)files.nextElement();  
  26.            type = multipartRequest.getContentType(name);   
  27.            filename = multipartRequest.getFilesystemName(name);   
  28.            originalFilename = multipartRequest.getOriginalFileName(name);            
  29.            File currentFile = multipartRequest.getFile(name);  
  30.            ...  
  31.     }  
  32.       
  33.     // 取得其它非文件字段   
  34.     Enumeration params = multipartRequest.getParameterNames();  
  35.       
  36.     while (params.hasMoreElements()) {  
  37.         String name = (String)params.nextElement();  
  38.         String value = multi.getParameter(name);  
  39.         ...  
  40.     }                        
  41. catch (Exception exception) {   
  42.     response.sendError(response.SC_METHOD_NOT_ALLOWED);  
  43. finally {   
  44.     if (out != null) {out.close();}   
  45. }  


3. SmartUpload示例代码:

view plaincopy to clipboardprint?
  1. smartupload mysmartupload = new smartupload();  
  2. mysmartupload.initialize(this.getServletConfig(), request, response);  
  3. // 设置文件大小限制(单位:字节)   
  4. mysmartupload.setMaxFileSize(10000000);             
  5. // 设置总上传数据总大小(单位:字节)   
  6. mysmartupload.setTotalMaxFileSize(20000000);  
  7. // 设置允许的文件扩展名   
  8. mysmartupload.setAllowedFilesList("jpg,png,gif,bmp,jpeg");  
  9. // 设置不允许的文件扩展名   
  10. mysmartupload.setDeniedFilesList("exe,bat,jsp,htm,html,,");  
  11.   
  12. try {  
  13.     mysmartupload.upload();  
  14. catch (smartuploadException e1) {  
  15.     e1.printStackTrace();  
  16. }  
  17.   
  18. // 读取其它非文件上传字段   
  19. com.jspsmart.upload.Request req = mysmartupload.getRequest();  
  20. String title = req.getParameter("dest");  
  21.   
  22. // 保存文件   
  23. for (int i = 0; i < mysmartupload.getFiles().getCount(); i++) {  
  24.     com.jspsmart.upload.File file = mysmartupload.getFiles().getFile(i);  
  25.       
  26.     if (file.isMissing()) continue;  
  27.   
  28.     try {  
  29.         file.saveAs("yourSavePath" + file.getFileName());  
  30.     } catch (smartuploadException e) {  
  31.         e.printStackTrace();  
  32.     }  
  33. }  

原创粉丝点击