背景
这是@RestController中定义的方法,它从磁盘读取文件然后流回。
@RequestMapping(value = "/bill", method = RequestMethod.GET)
public ResponseEntity<Object> getbill(){
...
InputStream in = new FileInputStream(file);
InputStreamResource inputStreamResource = new InputStreamResource(in);
httpHeaders.setContentLength(file.Length());
return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.OK);
}
问题
我想在请求送达后删除该文件,但找不到合适的位置。
我认为应该是在 inputStream 关闭之后( https://github.com/spring-projects/spring-framework/blob/v4.3.9.RELEASE/spring-web/src/main/java/org/springframework/http/converter/ResourceHttpMessageConverter.java#L117 )。由于文件是通过 Inputstream 打开的,因此无法在上述方法中完成。
答案摘要 感谢大家对此提供的帮助。
接受的答案需要最少的改变并且工作良好。
最佳答案
除了在 RESTfull 服务中对 GET 请求执行破坏性操作是不好的做法之外,默认 Java 库无法做到这一点。更广泛接受的实现是使用 GET 流式传输文件,然后调用 DELETE 来删除文件。
但是您可以通过实现自己的 InputStream 来做到这一点,请参阅 Stackoverflow 中的早期线程 deleting files on closing a InputStream .
关于java - Spring @RestController - 请求被处理后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52646608/