Spring上傳檔案java.lang.IllegalStateException: File has been moved - cannot be read again問題分析及解決
阿新 • • 發佈:2018-11-13
問題分析:
Spring上傳檔案預設的檔案上傳處理器 CommonsMultipartResolver 這個類中使用了 common fileUpload 元件來進行檔案的上傳。
而 fileUpload 元件在進行檔案上傳時因為 java 記憶體有限,所以會先將較大的檔案存放在硬碟中的一個臨時目錄中讀取,而不是直接在記憶體中進行操作。
因此,在對較大檔案進行分步驟操作時(例如對大小超過10M的圖片進行縮圖生成處理),就會因為要讀取的檔案已經不存在於記憶體中而出現java.lang.IllegalStateException: File has been moved - cannot be read again 這個異常。
解決方案:
CommonsMultipartResolver 這個類中 maxInMemorySize 這個屬性用來決定大小超多多大的檔案會被放在硬碟中的臨時目錄而不是直接在記憶體中操作,所以我們調整這個數值的大小為超過我們要進行操作的檔案的最大大小即可。
Spring MVC操作如下:
修改applicationcontext.xml檔案中如下屬性:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600"/>
<property name="maxInMemorySize" value="4096"/>//將此值設定為需要的大小即可
</bean>
Spring Boot操作如下:
@Bean(name = "multipartResolver")
public MultipartResolver multipartResolver(){
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setMaxInMemorySize(20 *1024*1024);//將此值設定為需要的大小即可,我這裡設定為20M
return resolver;
}
不過小弟覺得我的解決方式過於簡單粗暴,可能會有什麼問題是我沒考慮到的,如果各位前輩覺得我的處理方式不妥,還望各位前輩多多指點,先謝謝各位前輩了!