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.
try following:
ServletOutputStream outStream = response.getOutputStream();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename="DATA.ZIP"");
outStream.write(decodedBytes);
outStream.flush();