报错代码:
java.io.FileNotFoundException: /tmp/tomcat.1659982087389128076.8083/work/Tomcat/localhost/ROOT/upload_ae5c0e5e_0c20_4539_9172_f363d21426c8_00000016.tmp (没有那个文件或目录)
查看了不少资料,最后总结的问题是
file.transferTo(desc); 在读取后会将此file文件流关闭。导致后续对file操作时就会报错
解决方法(感谢群里的大佬):
1 public static final FileInfo uploadInvoice(String baseDir, MultipartFile file) 2 throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, 3 InvalidExtensionException 4 { 5 FileInfo fileInfo = new FileInfo(); 6 fileInfo.setFileOrgName(file.getOriginalFilename()); 7 int fileNamelength = file.getOriginalFilename().length(); 8 if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) 9 { 10 throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH); 11 } 12 13 assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); 14 15 String fileName = extractFilenameByDate(file); 16 String[] strings = fileName.split("/"); 17 fileInfo.setFileDir(strings[0]); 18 fileInfo.setFileName(strings[1]); 19 20 File desc = getAbsoluteFile(baseDir, fileName); 21 FileUtils.copyInputStreamToFile(file.getInputStream(),desc); //从流拷贝到文件 22 // file.transferTo(desc); // linux 环境报错 23 String pathFileName = getPathFileName(baseDir, fileName); 24 return fileInfo; 25 }
将file.transferTo()这个方法弃用,使用copyInputStreamToFile方法来进行文件的拷贝。这样可以避免此问题。
只作参考,写的不对的地方请帮忙指出,谢谢!