How to delete file after REST response

tarka picture tarka · Nov 14, 2014 · Viewed 12.1k times · Source

What is the best way to handle deleting a file after it has been returned as the response to a REST request?

I have an endpoint that creates a file on request and returns it in the response. Once the response has been dispatched the file is no longer needed and can/should be removed.

@Path("file")
@GET
@Produces({MediaType.APPLICATION_OCTET_STREAM})
@Override
public Response getFile() {

        // Create the file
        ...

        // Get the file as a steam for the entity
        File file = new File("the_new_file");

        ResponseBuilder response = Response.ok((Object) file);
        response.header("Content-Disposition", "attachment; filename=\"the_new_file\"");
        return response.build();

        // Obviously I can't do this but at this point I need to delete the file!

}

I guess I could create a tmp file but I would have thought there was a more elegant mechanism to achieve this. The file could be quite large so I cannot load it into memory.

Answer

cmaulini picture cmaulini · Jan 20, 2017

Use a StreamingOutput as entity:

final Path path;
...
return Response.ok().entity(new StreamingOutput() {
    @Override
    public void write(final OutputStream output) throws IOException, WebApplicationException {
        try {
            Files.copy(path, output);
        } finally {
            Files.delete(path);
        }
    }
}