我从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();
}
处理响应后删除此临时文件的正确方法是什么? JAX-RS实现(如Jersey)应该自动执行此操作吗?
答案 0 :(得分:0)
final File file;
return Response.ok((StreamingResult) output -> {
Files.copy(file.toPath(), output);
final boolean deleted = file.delete();
}).build();
答案 1 :(得分:0)
https://dzone.com/articles/jax-rs-streaming-response上的示例比Jin Kwon的简短答复更有帮助。
这里是一个例子:
public Response getDocumentForMachine(@PathParam("custno") String custno, @PathParam("machineno") String machineno,
@PathParam("documentno") String documentno, @QueryParam("language") @DefaultValue("de") String language)
throws Exception {
log.info(String.format("Get document. mnr=%s, docno=%s, lang=%s", machineno, documentno, language));
File file = new DocFileHelper(request).getDocumentForMachine(machineno, documentno, language);
if (file == null) {
log.error("File not found");
return Response .status(404)
.build();
}
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream out) throws IOException, WebApplicationException {
log.info("Stream file: " + file);
try (FileInputStream inp = new FileInputStream(file)) {
byte[] buff = new byte[1024];
int len = 0;
while ((len = inp.read(buff)) >= 0) {
out.write(buff, 0, len);
}
out.flush();
} catch (Exception e) {
log.log(Level.ERROR, "Stream file failed", e);
throw new IOException("Stream error: " + e.getMessage());
} finally {
log.info("Remove stream file: " + file);
file.delete();
}
}
};
return Response .ok(stream)
.build();
}