krohit krohit - 24 days ago 5x
Java Question

Zip file getting downloaded without .zip extension in Chrome through Java

  1. I am trying to download a zip file from a fixed location present in server.

  2. In my Rest method , I am just passing the file name from client (browser) .
    (Please see below code ).

  3. In my Rest method I am sending the zip file to the client.

  4. The file gets downloaded on the browser without any issue.

My Issue is that the zip file gets downloaded on browser without .zip extension.

@RequestMapping(value = "/zip/{filePath}", method = RequestMethod.GET)
public @ResponseBody void downloadZip(@PathVariable("filePath") String filePath, HttpServletRequest request, HttpServletResponse response) throws IOException {

ServletContext context = request.getServletContext();
File downloadFile = new File(filePath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get output stream of the response
OutputStream outStream = response.getOutputStream();

byte[] buffer = new byte[(int) downloadFile.length()];
int bytesRead = -1;

// write bytes read from the input stream into the output stream
while ((bytesRead = != -1) {
outStream.write(buffer, 0, bytesRead);
// get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
System.out.println("MIME type: " + mimeType);

// set content attributes for the response
response.setContentLength((int) downloadFile.length());

String.format("attachment; filename=\"%s\"", downloadFile.getName()));
logger.error("Filename = " + downloadFile.getName());

PS: The file gets downloaded on some machine with ZIP and in some machine without ZIP. I have tested only on chrome (as per client requirement).
I think, there is an issue with the Chrome settings which I need to look upon (just a guess).

Can someone help upon this?

Thanks in advance....


Change the order between setting the response headers and shoving the file down the output stream - after all, the headers need to leave first.


  1. "Why setting HttpServletResponse in starting effects the code."
    Well, simple: the client is supposed to receive instructions of what to do with the payload by interpreting the HTTP response headers. If those are not set in the beginning, sending those headers at the end of the transmission comes too late. And this assumes the HttpServletResponse will actually send those headers when invoked with setHeader, which is a big assumption - I suspect those headers will not actually be sent after calling response.getOutputStream - it is unlikely the response will buffer the entire payload to wait for the caller to specify those headers.