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 了。

 

希望各位 越来越好~

 

 

你可能感兴趣的:(java源代码,MultipartFile)