MultipartFile.transferTo(file); save temporary file error
Error message:
java.io.FileNotFoundException: C:\Users\XXX\AppData\Local\Temp\tomcat.9095.675054628671612619\work\Tomcat\localhost\ROOT\workspace\report-core\upload\zip\qq7TGXwf\010404.zip (the system cannot find to the specified path.)
error source
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); // delete after decompression file.delete(); } catch (IOException e) { System.out.println("Error"); log.error("", e); throw BusinessExceptionBuilder.build(ResponseCode.FAIL_CODE, e.getMessage()); } }
Because your file is a relative path, not an absolute path, there is no temporary file created at all, and the absolute path cannot be found.
Then the solution:
Import a jar package
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency>
Then modify the code that saves the temporary file
Replace MultipartFile.transferTo(file) with 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); // delete after decompression file.delete(); } catch (IOException e) { System.out.println("Error"); log.error("", e); throw BusinessExceptionBuilder.build(ResponseCode.FAIL_CODE, e.getMessage()); } }
Then it was solved perfectly. It took two hours. At first, I thought that the problem was caused by the Chinese name of C://User/. Later, the test was not because the temporary files were cleaned up, so