3

I have a zip file as a byte array (byte[]), I could write it to the file system using,

        FileOutputStream fos = new FileOutputStream("C:\\test1.zip");
        fos.write(decodedBytes);  // decodedBytes is the zip file as a byte array 
        fos.close();            

Instead of writing it to a file and reading it to make it as a download, I would like to make the byte array as a download directly, I tried this,

    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=\"File.zip\"");
    ServletOutputStream outStream = response.getOutputStream();
    outStream.write(decodedBytes);  // decodedBytes is the zip file as a byte array 

This is not working, I'm getting empty file. How can I make the byte array as a download?

Update: I added finally clause and closed the ServletOutputStream and it worked.

    }catch (Exception e) {
        Log.error(this, e);
    } finally {
        try{
            if (outStream != null) {
                outStream.close();              
            }
        } catch (IOException e) {
            Log.error(this, "Download: Error during closing resources");
        }
    }

Pankaj solution also works.

SyAu
  • 1,651
  • 7
  • 25
  • 47
  • Check this link: http://stackoverflow.com/questions/13989215/how-to-convert-a-byte-into-a-file-with-a-download-dialog-box – akhil_mittal Oct 15 '15 at 04:03
  • Did you make sure that `decodedBytes` actually has data in it? Have you tried _not_ zipping the data first? – Matt Ball Oct 15 '15 at 04:03
  • @MattBall I checked the length of byte[] in eclipse debug, it matches the physical zip file. Actually the byte[] comes from DB, which was already zipped and stored in a BLOB. – SyAu Oct 15 '15 at 04:09
  • outStream.flush() put after outstream.write() – Pankaj Saboo Oct 15 '15 at 04:14

1 Answers1

5

try following:

ServletOutputStream outStream = response.getOutputStream();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename="DATA.ZIP"");
outStream.write(decodedBytes);
outStream.flush();
Pankaj Saboo
  • 1,125
  • 1
  • 8
  • 27