Search code examples
javaplayframeworkplayframework-2.5

Playframework 2.5.0 : Unable to serve server-side generated zip file


My Playframework 2.5.0 application has to serve temporary created zip file. I create and fulfill the zip file in the /tmp directory, without any problem (I can open it in this place and extract the contained files).

But the file sent to the client seems to be truncated and can't be opened.

String tempPath = "/tmp/" + label + ".zip";

File zipFile = new File(tempPath);
zipFile.deleteOnExit();
ZipOutputStream zos = null;

try {
    zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));

    for (/* loops through files to zip */) {
        InputStream is = methodToGetTheDocument();
        ZipEntry zipEntry = new ZipEntry(document.getLabel());
        zos.putNextEntry(zipEntry);
        byte[] bytes = new byte[2048];
        int count = is.read(bytes);
        while (count > -1) {
            zos.write(bytes, 0, count);
            count = is.read(bytes);
        }
        is.close();
        zos.closeEntry();
    }
    return ok(zipFile);
} catch (Exception e) {
    return badRequest("Bad request");
} finally {
    try {
        zos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

I return a classical Result object... What is the problem ?


Solution

  • You have to "close" the zip file using zos.close() before you return ok(zipFile)