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

 

希望各位 越來越好~

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章