MultipartFile.transferTo(file);保存临时文件报错
报错信息:
java.io.FileNotFoundException: C:\Users\XXX\AppData\Local\Temp\tomcat.9095.675054628671612619\work\Tomcat\localhost\ROOT\workspace\report-core\upload\zip\qq7TGXwf\010404.zip (系统找不到指定的路径。)
错误源码
public static void decompress(MultipartFile zipFile, String dstPath) {
try {
File file = new File(dstPath + File.separator + zipFile.getOriginalFilename());
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
zipFile.transferTo(file);
decompress(new ZipFile(file), dstPath);
//解压完删除
file.delete();
} catch (IOException e) {
System.out.println("报错");
log.error("", e);
throw BusinessExceptionBuilder.build(ResponseCode.FAIL_CODE, e.getMessage());
}
}
因为你那个file是相对路径,并不是绝对路径,所以根本没有创建临时文件,找不到绝对路径
然后解决办法:
导入一个jar包
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
然后修改这个保存临时文件的那句代码
将MultipartFile.transferTo(file)替换为FileUtils.copyInputStreamToFile(MultipartFile.getInputStream(),file);
public static void decompress(MultipartFile zipFile, String dstPath) {
try {
File file = new File(dstPath + File.separator + zipFile.getOriginalFilename());
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
FileUtils.copyInputStreamToFile(zipFile.getInputStream(),file);
decompress(new ZipFile(file), dstPath);
//解压完删除
file.delete();
} catch (IOException e) {
System.out.println("报错");
log.error("", e);
throw BusinessExceptionBuilder.build(ResponseCode.FAIL_CODE, e.getMessage());
}
}
然后完美解决,花了两个小时,刚开始以为是C://User/中文名才引发的这个问题,后来测试并不是,是因为临时文件被清理了,所以
————————————————
版权声明:本文为优快云博主「努力的小玖心」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/qq_53121751/article/details/126666757