java上传图片MultipartFile,IllegalStateException: File has already been moved - cannot be transferred

之前在项目中遇到过java后台获取到上传的文件 MultipartFile ,业务中需要对该文件进行两次处理,结果发生异常。

使用情况 如下:

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String execute(@RequestParam( value = "newuserimage" ) MultipartFile multipartFile,
			HttpServletRequest request, HttpServletResponse response) throws IOException{
		multipartFile.transferTo(new File("D:\\study\\img\\b.jpg"));
		multipartFile.transferTo(new File("D:\\study\\img\\c.jpg"));
		return "other";
	}

会出现如下异常:

java.lang.IllegalStateException: File has already been moved - cannot be transferred again
	at org.springframework.web.multipart.commons.CommonsMultipartFile.transferTo(CommonsMultipartFile.java:133)
	at com.sinotrans.controller.ImgInfoController.execute(ImgInfoController.java:26)

异常的原因很简单,就是 MultipartFile 对象被重复使用了,该对象已经被转换到 file 对象中,不能重复使用。

这说明 transferTo 方法影响到了原 MultipartFile 对象。

解决办法,使用输出流的方式,把 MultipartFile 对象输出到 文件对象中,这样不会影响原 MultipartFile 对象。如下:

		this.inputStreamToFile((FileInputStream) multipartFile.getInputStream(), new File("D:\\study\\img\\b.jpg"));
		this.inputStreamToFile((FileInputStream) multipartFile.getInputStream(), new File("D:\\study\\img\\c.jpg"));
	public void inputStreamToFile(InputStream ins, File file) {
	    try {
	        OutputStream os = new FileOutputStream(file);
	        int bytesRead = 0;
	        byte[] buffer = new byte[8192];
	        while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
	            os.write(buffer, 0, bytesRead);
	        }
	        os.close();
	        ins.close();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}

这样就ok 了。

 

希望各位 越来越好~

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值