Search code examples
javarestjerseyjax-rs

How to clean up temporary file after response in JAX-RS REST Service?


I am returning a temporary file from my JAX-RS REST Service like below:

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

What is the correct way of removing this temporary file after the response has been processed? Is the JAX-RS implementation (like Jersey) supposed to do this automatically?


Solution

  • You can pass an instance of StreamingOutput that copies the content of the source file to the client output and eventually deletes the file.

    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();
    
    final File file = getTheFile();
    return Response.ok((StreamingOutput) output -> {
            final long copied = Files.copy(file.toPath(), output);
            final boolean deleted = file.delete();
        }).build();