1

I am trying to add a function to my web app which lets the users download an excel file.

I'm trying to achieve this with the following code:

@Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        File file = new File("d:/test/test.xls");
        response.setContentType("application/xls");
        response.addHeader("Content-Disposition", "attachment; filename=test.xls");
        response.setContentLength((int) file.length());

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            OutputStream responseOutputStream = response.getOutputStream();
            int bytes;
            while ((bytes = fileInputStream.read()) != -1) {
                responseOutputStream.write(bytes);
            }
            fileInputStream.close();
            responseOutputStream.close();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

I'm able to download the excel file with the above code, however the file is corrupted. If I open it with microsoft excel, I get a popup with the message:

"the file format and extension of don't match. the file could be corrupted or unsafe".

And the excel file is empty.

After running the code, the original file(d:/test/test.xls) gets also corrupted.

What am I doing wrong?

MeesterPatat
  • 2,671
  • 9
  • 31
  • 54

2 Answers2

3

The official MIME type for Excel file .xls is application/vnd.ms-excel and for .xlsx is application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.

Also, I would suggest doing response.reset() prior to writing to the output stream and responseOutputStream.flush() (important) prior to closing the response.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
0

Try below code :

    File file = null;
    InputStream in = null;
    OutputStream outstream = null;
    try {
      response.reset();
      in = new FileInputStream(file);
      response.setContentType("application/vnd.ms-excel");
      response.addHeader("content-disposition", "attachment; filename=data.xls");
      outstream = response.getOutputStream();
      IOUtils.copyLarge(in, outstream);
     }
    catch (Exception e) {
        out.write("Unable to download file");
    }finally {
        IOUtils.closeQuietly(outstream);
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        if (file != null)
            file.delete();
    }

dont forgot to add apache commons-io-2.4 in your dependency

Keval
  • 1,857
  • 16
  • 26