I want to delete the downloaded file

Asked 1 years ago, Updated 1 years ago, 107 views

I use JAX-RS to create a WebAPI where I can download files.
I want to delete this file immediately after downloading it, but I don't know how to do it.

@GET
@ Path ("download")
public Response download() {

    ...

    try(valis=Files.newInputStream(fileInfo.getPath(), StandardOpenOption.DELETE_ON_CLOSE)){
        val response=Response.ok(is,fileInfo.getMimeType()) .encoding("UTF-8")
                .header("Content-Disposition", contentDisposition(fileInfo))).build();
        return response;
    }
}

For example, if you make it like this, you will get ClosedChannelException.
Perhaps JAX-RS has failed to pass the file binaries to HTTP clients since it will be closed and deleted when it leaves this method (or try clause).

Is there any good way?

java java-ee

2022-09-30 21:28

2 Answers

I can't detect that the download is complete, so if the file size is small, why don't you delete the file after converting it to ByteArrayInputStream?

I don't know when the file will be created, but I think it would be better to consider sending the data directly to the stream instead of creating the file.


2022-09-30 21:28

If you don't have any reason to download the output file (e.g., the file is generated by an external command), it's better to flow the data directly into the stream instead of creating the file.

If there is any reason, you may want to create StreamingOutput, create a Response, download it, and delete the file with File#delete() after the output is complete.

package com.example;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produce;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

@ Path ("download")
public class FileDownload {

    /**
     * Exported the CSV file to a temporary file and downloaded it. Delete temporary files after download is complete.
     *
     * @return
     * @throws IOException
     */
    @ GET
    @Path("csvfromfile")
    @Produce("text/plain")
    publicResponse downloadCsvFromFile()throws IOException {
        System.out.println("Hello!");

        // output temp csv file
        File tmpFile=File.createTempFile("download", ".csv");
        System.out.printf("tmpFile=>%s\n", tmpFile);
        try(BufferedWriter writer = new BufferedWriter(newOutputStreamWriter(newFileOutputStream(tmpFile), "UTF-8")){

            int lineNumber = 0;
            while(lineNumber<10000){
                lineNumber++;
                writer.write(String.format("%06d", lineNumber");
                writer.newLine();
            }
            writer.flush();
        }

        // Create StreamingOutput
        StreamingOutputstream=(OutputStream out)->{
            Files.copy(tmpFile.toPath(), out);
            System.out.printf("try to delete tmpFile(%s),\n", tmpFile);
            boolean deleteOk=tmpFile.delete();
            System.out.printf("delete tmpFile(%s)is%b!\n", tmpFile, deleteOk);
        };

        // Create and return a Response based on StreamingOutput
        return Response.ok(stream).header("Content-Disposition", "attachment; filename=hello.csv") .build();
    }

    /**
     * Export the CSV file directly to StreamingOutput and download the file
     *
     * @return
     */
    @ GET
    @Path("csv")
    @Produce("text/plain")
    public Response filedownload() {
        StreamingOutputstream=(OutputStream out)->{
            try(BufferedWriter writer = new BufferedWriter(newOutputStreamWriter(out, "UTF-8")){

                writer.write("LineNumber");
                writer.newLine();
                int lineNumber = 10000;
                while(lineNumber>0){
                    String lineData = String.format ("%06d", lineNumber);
                    writer.write(lineData);
                    writer.newLine();

                    lineNumber --;

                }
                writer.flush();
            }
        };

        // return a response
        return Response.ok(stream).header("Content-Disposition", "attachment; filename=hello.csv") .build();
    }

}


2022-09-30 21:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.