ab2*_*000 1 java rest jax-rs jersey
我正在从 JAX-RS REST 服务返回一个临时文件,如下所示:
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile() {
File file = ... // create a temporary file
return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" ) //optional
.build();
}
Run Code Online (Sandbox Code Playgroud)
处理响应后删除此临时文件的正确方法是什么?JAX-RS 实现(如 Jersey)是否应该自动执行此操作?
您可以传递一个实例,StreamingOutput该实例将源文件的内容复制到客户端输出并最终删除该文件。
final Path path = getTheFile().toPath();
final StreamingOutput output = o -> {
final long copied = Files.copy(path, o);
final boolean deleted = Files.deleteIfExists(path);
};
return Response.ok(output).build();
Run Code Online (Sandbox Code Playgroud)
final File file = getTheFile();
return Response.ok((StreamingOutput) output -> {
final long copied = Files.copy(file.toPath(), output);
final boolean deleted = file.delete();
}).build();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1775 次 |
| 最近记录: |