上傳Excel進行處理 不用用戶等待 處理完以後 會郵件告知處理結果
因此是異步處理java
public void readExcel(@RequestParam("file") MultipartFile file) { CompletableFuture.runAsync(() -> { try { service.readExcel(file); } catch (IOException e) { e.printStackTrace(); } }); }
實際使用的過程當中 發現常常上傳失敗 報錯以下web
java.io.FileNotFoundException: /private/tmp/upload_2cc08ec8_c3eb_4633_8c0f_0cc20e34ff55_00000000.tmp (No such file or directory) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.<init>(FileInputStream.java:138) at org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.getInputStream(DiskFileItem.java:188) at org.apache.catalina.core.ApplicationPart.getInputStream(ApplicationPart.java:100) at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile.getInputStream(StandardMultipartHttpServletRequest.java:297)
請求返回後 會自動刪除臨時文件 致使實際讀取Excel的時候 找不到文件spring
// org.apache.catalina.core.ApplicationPart#delete public void delete() throws IOException { fileItem.delete(); }
複製該臨時文件 將複製後的文件傳給異步程序處理 處理完以後刪除該臨時文件apache
String uuid = UUID.randomUUID().toString().replace('-', '_'); String tmpFileName = String.format("/tmp/upload_%s.tmp", uuid); final File tmpFile = new File(tmpFileName); try { Files.copy(file.getInputStream(), tmpFile.toPath()); } catch (IOException e) { e.printStackTrace(); } CompletableFuture.runAsync(() -> { try { service.readExcel(tmpFile); } catch (IOException e) { e.printStackTrace(); } });