Search code examples
javagoogle-chromedownloadzipmicrosoft-edge

Zip file downloading as HTML


I am using a Java web application to create a zip file using the response output stream, and setting the response headers.

When Chrome/Edge come to download the file, they treat it as an html file rather than a zip.

renaming the .html that is downloaded to .zip then gives the correct file, so I'm creating the zip correctly.

If I set Edge to prompt for download, rather than automatically download files, I can then treat it as a zip on download.

IE11 correctly downloads as a zip.

What am I doing wrong in my code?

ServletOutputStream servletOutputStream = response.getOutputStream();
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(servletOutputStream));
zos.putNextEntry(new ZipEntry(file.getName()));
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis= new BufferedInputStream(fis);

// Write the contents of the file
int data = 0;
while ((data = bis.read()) != -1) 
{
   zos.write(data);
}
bis.close();
fis.close();
zos.flush();
zos.closeEntry();
zos.close();
servletOutputStream.close();

response.setContentType("Content-type: text/zip");
response.setHeader("Content-Disposition", "attachment; filename=fileName.zip");


Solution

  • Try setting the headers first before you do anything else