This question already has an answer here:
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.
save the response in a tmp variable with replacing your return statement like this:
Without knowing the context of your application, you can delete the file when the VM exits:
See: https://docs.oracle.com/javase/7/docs/api/java/io/File.html#deleteOnExit%28%29
There is a more elegant solution, don't write a file, just write directly to the output stream contained in the instance of
Response
.send file name on response:
after that you can send delete restful method
Use a StreamingOutput as entity: