Search code examples
javagoogle-app-engineservletsmemoryunzip

Unzip in memory for google App Engine Java


I would like to unzip a file uploaded to a servlet, and store all decompressed files to the DataStore as byte[]. Since there is no file system in GAE, I have to put everything in memory. Suppose I have byte[] allzipdata to store the original zip file data. How do I unzip the file and especially how to get inputstream from each zipentry which are in memory?

ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(allzipdata));
ZipEntry ze = zis.getNextEntry();
while(ze!=null){
}

So what's in the while loop?

Also, if I upload a file, I know the contentType using item.getContentType(); in which item is a FileItemStream. So for a zipentry, is there a way to know the contentType?


Solution

  • To read image data from the ZipInputStream I'd recommend to use the Apache Commons-IO library. It converts the ZIP entry of the input stream to a byte array:

        ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(allzipdata));
        ZipEntry ze = null;
        while ((ze = zis.getNextEntry()) != null) {
           // write your code to use zip entry e.g. below:
           String filename = ze.getName();
           System.out.println("File Name of Entry file="+fileName);
           byte[] data = IOUtils.toByteArray(zis);
           // now work with the image `data`
        }