0

I have the following servlet that downloads a xlsx file, however the file is corrupted when downloaded. The original file is 12.8 KB, but the downloaded one is 20.8 KB

Below is my code

    public class MyServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            try {
                String fileName = "MyFile.xlsx";
                URL url = getClass().getResource("/" + fileName);
                File f = new File(url.getPath());
    
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment; filename="+fileName);
                response.setHeader("Pragma", "public");
                response.setHeader("Cache-Control", "no-store");
                response.addHeader("Cache-Control", "max-age=0");
                FileInputStream fin = null;
                try {
                    fin = new FileInputStream(f);
                } catch (final FileNotFoundException e) {
                    e.printStackTrace();
                }
                final int size = 1024;
                try {
                    response.setContentLength(fin.available());
                    final byte[] buffer = new byte[size];
                    ServletOutputStream os = null;
                os = response.getOutputStream();
                int length = 0;
                while ((length = fin.read(buffer)) != -1) {
                    os.write(buffer, 0, length);
                }
                fin.close();
                os.flush();
                os.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }catch (final Exception ex){

        }
    }
}

Any idea why this happening?

Amit Kumar Lal
  • 5,537
  • 3
  • 19
  • 37
Arya
  • 8,473
  • 27
  • 105
  • 175
  • Hello, maybe it is because of the content-type have a look [here](https://stackoverflow.com/a/2938188/4333961) and try other content-type. – alexandrum Sep 28 '20 at 20:50
  • You should remove all catch except the outer one and add error messages (or error page handler) to log something in case you are skipping over an exception. This code won't run if the resources are in a jar or war file as `url.getPath()` won't resolve to a File. – DuncG Sep 29 '20 at 16:26
  • Perhaps you have more than one directory inside the classpath which contains a different copy of "MyFile.xlsx"? – DuncG Sep 30 '20 at 10:20

0 Answers0