users@jersey.java.net

[Jersey] Receiving large multipart file in Jersey server

From: Mikael Ståldal <mikael.staldal_at_appearnetworks.com>
Date: Fri, 6 Feb 2015 18:14:38 +0100

I am implementing a server with Jersey which have an endpoint receiving a
multipart/form-data entity with two parts. The first part is a short
string, and the second part is a possibly large zip file.

I need to extract some entries from the zip file (using java.util.zip
stuff), and then store the whole zip file on disk. I do not want to buffer
the whole zip file in memory.

How can I do that in an efficient way?

My current implementation uses jersey-media-multipart and do like below.
However, it seems like the implementation uses it's own temporary files
(named MIME*.tmp), so it seems redundant that I also create a temp file.
Can I get access to the implementation temp file somehow?

And it seems like the implementation's temp file is not properly cleaned up
if the file upload is cancelled in the middle.

    @Consumes({MediaType.MULTIPART_FORM_DATA})
    @POST
    public void endpoint(@FormDataParam("name") String name,
                         @FormDataParam("file") InputStream file) throws
IOException {

        File tempFile = File.createTempFile("file", null);
        try {
            org.apache.commons.io.FileUtils.copyInputStreamToFile(file,
tempFile);

            ZipFile zipFile = new ZipFile(tempFile);
            // extract some entries from the ZipFile here
            zipFile.close();

            Path destinationPath = calcPath(name);
            Files.move(tempFile.toPath(), destinationPath,
StandardCopyOption.REPLACE_EXISTING);
        } finally {
            tempFile.delete();
        }
    }


-- 
Mikael Ståldal
Chief Software Architect
*Appear*
Phone: +46 8 545 91 572
Email: mikael.staldal_at_appearnetworks.com