ag.albachicar
ag.albachicar

Reputation: 357

How to execute code after return Result in java Play! Framework?

I am using Play! Framework 2.2.1 and I want to stream a file created on the go. After the file is completely streamed I want to clean it up but I have not got any context to do so.

Is there any annotation or callback available for this kind of operation?

Upvotes: 4

Views: 1119

Answers (1)

biesior
biesior

Reputation: 55798

You can copy file content to the FileInputStream, delete the file and then return the stream, anyway, you need to set some headers basing on original file i.e. if you produce ZIPs it can be (pseudo code!):

public static Result file() {

    File tmpFile = new File("/path/to/your/generated.zip");

    FileInputStream fin = null;
    try {
        fin = new FileInputStream(tmpFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    response().setHeader("Content-disposition", "attachment;filename=" + tmpFile.getName());
    response().setHeader(CONTENT_TYPE, "application/zip");
    response().setHeader(CONTENT_LENGTH, tmpFile.length() + "");

    tmpFile.delete();

    return ok(fin);
}

Other option is writing temporary files to dedicated folder and returning them with common ok(file); so you don't need to care about creation of headers, anyway you need to write scheduler task which will delete files older than n minutes/hours every x minutes.

Upvotes: 2

Related Questions