I have created the zip file (sample.zip) which has some files with no issues. When I open the sample.zip, it contains the file which expected.
I want to put that zip file into http response. Currently I am using the following:
response.setContentType("application/zip");
response.addHeader("Content-Disposition", "attachment; filename="+"sampleZip.zip");
response.setContentLength(2048);
response.setHeader("Set-Cookie", "fileDownload=true; path=/");
FileInputStream fileInputStream = new FileInputStream("sample.zip");
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
response.flushBuffer();
Now its download the zip file in my browser default download location. But when I open that zip file it showing
Cannot open file: it does not appear to be valid archive
Kindly help me to fix this please.
This code looks good to me. But you are setting a default content length which might be the issue. Create File instanceand use the file.length() method to set the content length ans use the same file for your input stream. Also reading byte by byte is not a good idea. If possible use apache's IOUtils.copy() to copy data from your input stream to the ServletOutputStream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With