我正在使用Web API(使用Spring Boot)进行工作,该Web API使用外部C ++ api转换pdf,该程序正在运行,但是当我要在正文响应中发送文件时,出现此错误:
{
"timestamp": "2019-04-10T09:56:01.696+0000",
"status": 500,
"error": "Internal Server Error",
"message": "file [D:\\[Phenix-Monitor]1.pdf] cannot be resolved in the file system for checking its content length",
"path": "/convert/toLinPDf"}
控制器:
@PostMapping("/toLinPDf")
public ResponseEntity<ByteArrayResource> convertion(@RequestParam(value = "input", required = false) String in,
@RequestParam(value = "output", required = false) String out) throws IOException, InterruptedException {
linearizeService.LinearizePDf(in, out);
FileSystemResource pdfFile = new FileSystemResource(out);
return ResponseEntity
.ok()
.contentLength(pdfFile.contentLength())
.contentType(
MediaType.parseMediaType("application/pdf"))
.body(new ByteArrayResource(IOUtils.toByteArray(pdfFile.getInputStream())));
}
我想问题出在linearizeService.LinearizePDf(in, out);
中,因为在这种方法中我正在使用外部进程,所以发生的是,当我尝试使用FileSystemResource pdfFile = new FileSystemResource(out);
打开文件时,linearizeService确实做了尚未完成处理,为什么我会收到此错误,我的问题是:我该如何处理,我的意思是如何等待文件创建后再发送该文件?
答案 0 :(得分:1)
我建议您使用Java 8的Future API
。
这是您资源的更新。
@PostMapping("/toLinPDf")
public ResponseEntity<ByteArrayResource> convertion(
@RequestParam(value = "input", required = false) String in,
@RequestParam(value = "output", required = false) String out) throws IOException, InterruptedException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Callable<String> callable = () -> {
linearizeService.LinearizePDf(in, out);
return "Task ended";
};
Future<String> future = executorService.submit(callable);
String result = future.get();
executorService.shutdown();
FileSystemResource pdfFile = new FileSystemResource(out);
return ResponseEntity
.ok()
.contentLength(pdfFile.contentLength())
.contentType(
MediaType.parseMediaType("application/pdf"))
.body(new ByteArrayResource(IOUtils.toByteArray(pdfFile.getInputStream())));
}