Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write zip file into httpresponse

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.

like image 829
Krishnan Avatar asked Sep 13 '26 18:09

Krishnan


1 Answers

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.

like image 123
pravat Avatar answered Sep 15 '26 07:09

pravat