Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete file after REST response [duplicate]

Tags:

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.

like image 810
tarka Avatar asked Nov 14 '14 12:11

tarka


1 Answers

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);         }     } } 
like image 147
cmaulini Avatar answered Sep 28 '22 04:09

cmaulini