Search code examples
javaspringmodel-view-controllerdownloadzipinputstream

How to convert a byte array to ZIP file and download it using Java?


I need to write a code to convert a byte array to ZIP file and make it download in Spring MVC.

Byte array is coming from a webservice which is a ZIP file originally. ZIP file has a folder and the folder contains 2 files. I have written the below code to convert to byte array to ZipInputStream. But I am not able to convert into ZIP file. Please help me in this.

Here is my code.

ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(bytes));
ZipEntry entry = null;
while ((entry = zipStream.getNextEntry()) != null) {

    String entryName = entry.getName();

    FileOutputStream out = new FileOutputStream(entryName);

    byte[] byteBuff = new byte[4096];
    int bytesRead = 0;
    while ((bytesRead = zipStream.read(byteBuff)) != -1)
    {
        out.write(byteBuff, 0, bytesRead);
    }

    out.close();
    zipStream.closeEntry();
}
zipStream.close(); 

Solution

  • I am presuming here that you want to write a byte array to a ZIP file. As the data sent is also a ZIP file and to be saved is also ZIP file, shouldn't be a problem.

    Two steps are needed: save it on disk and return the file.

    1) Save on disk part:

    File file = new File(/path/to/directory/save.zip);
        if (file.exists() && file.isDirectory()) {
            try {
                OutputStream outputStream = new FileOutputStream(new File(/path/to/directory/save.zip));
                outputStream.write(bytes);
                outputStream.close();
            } catch (IOException ignored) {
    
            }
        } else {
            // create directory and call same code
        }
    }
    

    2) Now to get it back and download it, you need a controller :

    @RequestMapping(value = "/download/attachment/", method = RequestMethod.GET)
    public void getAttachmentFromDatabase(HttpServletResponse response) {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getFileName() + "\"");
        response.setContentLength(file.length);
    
        FileCopyUtils.copy(file as byte-array, response.getOutputStream());
        response.flushBuffer();
    }
    

    I have edited the code I have, so you will have to make some changes before it suits you 100%. Let me know if this is what you were looking for. If not, I will delete my answer. Enjoy.