• 转:upload.parseRequest为空


    FileItemFactory factory = new DiskFileItemFactory();  
    ServletFileUpload upload = new ServletFileUpload(factory);  
    upload.setHeaderEncoding("UTF-8");  
    List items = upload.parseRequest(request);   

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

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

     
      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= "上传文件扩展名是不允许的扩展名。 只允许" + 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.         }    
  • 相关阅读:
    自用类库整理之SqlHelper和MySqlHelper
    如何设置root登录(滴滴云)
    linux下载命令wget
    linux下查看已经安装的jdk 并卸载jdk
    Angular之constructor和ngOnInit差异及适用场景(转)
    【Spring Boot-技巧】API返回值去除为NULL的字段
    jackson 实体转json 为NULL或者为空不参加序列化
    Android 将Android项目打包成aar文件
    Linux修改war包中文件
    Android 7.0 Gallery图库源码分析4
  • 原文地址:https://www.cnblogs.com/blueherb/p/3998583.html
Copyright © 2020-2023  润新知