前端上傳失敗效果:
后端對(duì)應(yīng)的異常輸出信息:
關(guān)鍵信息:
java.io.IOException: java.io.FileNotFoundException: C:\Users\brendon\AppData\Local\Temp\tomcat.6510816303036534023.8099\work\Tomcat\localhost\ROOT\invoice\originalfile\2023-02-13\73432e18330dec9a05af2e74d068bfba83e0a88d.pdf (系統(tǒng)找不到指定的路徑。)
Caused by: java.io.FileNotFoundException: C:\Users\brendon\AppData\Local\Temp\tomcat.6510816303036534023.8099\work\Tomcat\localhost\ROOT\invoice\originalfile\2023-02-13\73432e18330dec9a05af2e74d068bfba83e0a88d.pdf (系統(tǒng)找不到指定的路徑。)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.(FileOutputStream.java:213)
at java.io.FileOutputStream.(FileOutputStream.java:162)
at org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.write(DiskFileItem.java:406)
at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:120)
… 92 more
此時(shí)后端對(duì)應(yīng)的上傳關(guān)鍵代碼:
//通過SHA1生成唯一文件名
String filename = hex.replaceAll("-","") + "." + suffix;
String fullPath = savePath +"/"+ filename;
System.out.println(fullPath);
try {
//將文件保存指定目錄
file.transferTo(new File(fullPath));
} catch (Exception e) {
e.printStackTrace();
resultView.setCode(ResultEnums.FAILURE.getCode());
resultView.setMsg(ResultEnums.FAILURE.getMessage()+"保存文件異常");
return resultView;
}
原因分析:
運(yùn)行在保存文件 file.transferTo(new File(fullPath))處報(bào)錯(cuò):
String fullPath = savePath +"/"+ filename;
是相對(duì)路徑,指向invoice\originalfile\2023-02-13\73432e18330dec9a05af2e74d068bfba83e0a88d.pdf
file.transferTo 方法調(diào)用時(shí),判斷如果是相對(duì)路徑,則使用temp目錄,即C:\Users\brendon\AppData\Local\Temp\tomcat.6510816303036534023.8099\work\Tomcat\localhost\ROOT
位置不對(duì),沒有此目錄存在,所以報(bào)錯(cuò)。
解決方案:transferTo 傳入?yún)?shù)定義為絕對(duì)路徑
關(guān)鍵代碼:
File currFile = new File(new File(savePath).getAbsolutePath()+"/" + filename);
file.transferTo(currFile);
文章來源:http://www.zghlxwxcb.cn/news/detail-657143.html
最終成功效果:
至此解決問題。文章來源地址http://www.zghlxwxcb.cn/news/detail-657143.html
到了這里,關(guān)于上傳文件提示java.io.IOException: java.io.FileNotFoundException:(系統(tǒng)找不到指定的路徑。)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!