struts2 parseRequest(request)为空替代方法

赠人玫瑰,手留余香.人生最大的快乐不在于占有什么而在于追求什么的过程.

参考文章:http://blog.csdn.net/happywzc110/article/details/7819037  http://hi.baidu.com/gujianting2010/item/ceb136f4a85ad0d26325d220                http://bbs.csdn.net/topics/390327422   http://bbs.csdn.net/topics/380264143

结合sturts2做文件上传的使用,如果使用common fileupload架包中的方法:

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List items = upload.parseRequest(request);
  在parseRequest的时候,经常会得到null。导致原因是struts2把原始的原来S2为简化上传功能,把所有的enctype="multipart/form-data"表单做了wrapper,最后把HttpServletResquest封装成 org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper 。


解决办法:imgFile:为input name=“imgFile”

MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request; 
		File file = wrapper.getFiles("imgFile")[0]; 
		String fileName = wrapper.getFileNames("imgFile")[0];
		//检查文件大小
		if(file.length() > maxSize){
			String temStr= "上传文件大小超过限制。";
			this.writeResponse(response, temStr);
			return;
		}
		//检查扩展名
		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
		if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
			String temStr= "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。";
			this.writeResponse(response, temStr);
			return;
		}

		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;

		try {  
            InputStream in = new FileInputStream(file);  
            File uploadFile = new File(savePath, newFileName);  
            OutputStream out = new FileOutputStream(uploadFile);  
            byte[] buffer = new byte[1024 * 1024];  
            int length;  
            while ((length = in.read(buffer)) > 0) {  
                out.write(buffer, 0, length);  
            }  
  
            in.close();  
            out.close();  
        } catch (FileNotFoundException ex) {  
            ex.printStackTrace();  
        } catch (IOException ex) {  
            ex.printStackTrace();  
        }  



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值