Подтвердить что ты не робот

Как удалить файл после ответа REST

Каков наилучший способ обращения с удалением файла после его возврата в ответ на запрос REST?

У меня есть конечная точка, которая создает файл по запросу и возвращает его в ответ. После отправки ответа файл больше не нужен и может/должен быть удален.

@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!

}

Я думаю, я мог бы создать файл tmp, но я бы подумал, что для этого есть более элегантный механизм. Файл может быть довольно большим, поэтому я не могу загрузить его в память.

4b9b3361

Ответ 1

Существует более элегантное решение, не записывайте файл, просто пишите непосредственно в выходной поток, содержащийся в экземпляре Response.

Ответ 2

Использовать StreamingOutput как сущность:

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

Ответ 4

В последнее время я сделал что-то подобное в разработке службы отдыха с использованием трикотажа

@GET
@Produces("application/zip")
@Path("/export")
public Response exportRuleSet(@QueryParam("ids") final List<String> ids) {

    try {
        final File exportFile = serviceClass.method(ruleSetIds);

        final InputStream responseStream = new FileInputStream(exportFile);


        StreamingOutput output = new StreamingOutput() {
            @Override
            public void write(OutputStream out) throws IOException, WebApplicationException {  
                int length;
                byte[] buffer = new byte[1024];
                while((length = responseStream.read(buffer)) != -1) {
                    out.write(buffer, 0, length);
                }
                out.flush();
                responseStream.close();
               boolean isDeleted = exportFile.delete();
                log.info(exportFile.getCanonicalPath()+":File is deleted:"+ isDeleted);                 
            }   
        };
        return Response.ok(output).header("Content-Disposition", "attachment; filename=rulset-" + exportFile.getName()).build();
    }

Ответ 5

сохранить ответ в переменной tmp с заменой оператора return следующим образом:

Response res = response.build();
//DELETE your files here.
//maybe this is not the best way, at least it is a way.
return res;

Ответ 6

отправить имя файла в ответ:

return response.header("filetodelete", FILE_OUT_PUT).build();

после этого вы можете отправить метод удаления restful

@POST
@Path("delete/{file}")
@Produces(MediaType.TEXT_PLAIN)
public void delete(@PathParam("file") String file) {

    File delete = new File(file);

    delete.delete();

}