upload.parseRequest为空

来源:互联网 发布:js胶做防水可以吗 编辑:程序博客网 时间:2024/05/22 10:53
转载:http://blog.csdn.net/happywzc110/article/details/7819037
[java]
 view plaincopy
  1. FileItemFactory factory = new DiskFileItemFactory();  
  2. ServletFileUpload upload = new ServletFileUpload(factory);  
  3. upload.setHeaderEncoding("UTF-8");  
  4. List items = upload.parseRequest(request);  
转载:http://blog.csdn.net/happywzc110/article/details/7819037

上传是items一直是空list。导致原因是struts2把原始的原来S2为简化上传功能,把所有的enctype="multipart/form-data"表单做了wrapper最后把HttpServletResquest封装成 org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper 怪不得我的 ServletFileUpload.parseRequest(request)不行!!! 

看我怎么改!废话不多说,直接贴代码!

[java] view plaincopy
  1. MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;   
  2.         File file = wrapper.getFiles("imgFile")[0];   
  3.         String fileName = wrapper.getFileNames("imgFile")[0];  
  4.         //检查文件大小  
  5.         if(file.length() > maxSize){  
  6.             String temStr= "上传文件大小超过限制。";  
  7.             this.writeResponse(response, temStr);  
  8.             return;  
  9.         }  
  10.         //检查扩展名  
  11.         String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();  
  12.         if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){  
  13.             String temStr= "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。";  
  14.             this.writeResponse(response, temStr);  
  15.             return;  
  16.         }  
  17.   
  18.         SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");  
  19.         String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;  
  20.   
  21.         try {    
  22.             InputStream in = new FileInputStream(file);    
  23.             File uploadFile = new File(savePath, newFileName);    
  24.             OutputStream out = new FileOutputStream(uploadFile);    
  25.             byte[] buffer = new byte[1024 * 1024];    
  26.             int length;    
  27.             while ((length = in.read(buffer)) > 0) {    
  28.                 out.write(buffer, 0, length);    
  29.             }    
  30.     
  31.             in.close();    
  32.             out.close();    
  33.         } catch (FileNotFoundException ex) {    
  34.             ex.printStackTrace();    
  35.         } catch (IOException ex) {    
  36.             ex.printStackTrace();    
  37.         }    

转载:http://blog.csdn.net/happywzc110/article/details/7819037

0 0