如何在JAX-RS REST服务中响应后清理临时文件?

时间:2015-08-18 05:16:16

标签: java rest jersey jax-rs

我从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)应该自动执行此操作吗?

2 个答案:

答案 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();
}