Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a zip file to the browser via the response OutputStream?

In this situation, I have created a zip file containing search result files, and am trying to send it to the user. Here is the chunk of code I am currently trying to use.

File[] zippable = new File[files.size()];
File resultFile = ZipCreator.zip(files.toArray(zippable), results);
InputStream result = new FileInputStream(resultFile);
IOUtils.copy(result, response.getOutputStream());

However, this currently doesn't work quite right. Instead of returning the zip file that I have created, it returns an html file. If I manually change the file extension afterwards, I can see that the contents of the file are still the search results that I need. So the problem just lies in returning the proper extension to the response.

Does anyone have any advice for this situation?

like image 942
Bennie Avatar asked Jan 11 '12 16:01

Bennie


2 Answers

You need to set the Content-Type response header to the value application/zip (or application/octet-stream, depending on the target browser). Additionally, you may want to send additional response headers indicating attachment status and filename.

like image 155
maerics Avatar answered Sep 21 '22 02:09

maerics


You need to set the content type header to application/octet-stream prior to streaming the results. Depends on what implementation of response you are using on how you actually do this.

like image 29
Jeff Foster Avatar answered Sep 21 '22 02:09

Jeff Foster