0
votes

In my application, I have an option to download the excel file from the folder by the user, all functions are working well but it shows only the response in the console and I can not download the excel file at the same time the browser does not show the save or download option.

Note : I used all possible ContentType("application/vnd.openxmlformats officedocument.spreadsheetml.sheet").

 String downloadFolder = request.getRealPath(fileDetail.getFilePath()+fileDetail.getFileName());

    Path file = Paths.get(downloadFolder);
    if(Files.exists(file)){
        response.reset();
        response.setContentType("application/vnd.openxmlformats officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"Demo.xlsx");

        try {
            Files.copy(file, response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e){
            return null;
        }
    }

How can I solve this problem? I need to download the excel file when the method is called.Thank you

3
Why do you want to open xlsx file in Notepad++? - Naveen Kumar
And the problem is what exactly? Do you expect to be able to view an .xls in Notepad? Does not seem like you should be able to to me. - Matt Clark
I want to download the excel file from the folder using java - Naveen
How can I download the excel file from a folder using java - Naveen

3 Answers

1
votes

You can try writing the file as belows

InputStream inputStream = new BufferedInputStream(new FileInputStream(file));

  //Copy bytes from source to destination(outputstream in this example), closes both streams.

  FileCopyUtils.copy(inputStream, response.getOutputStream());

0
votes

Try this for downloading file

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");


     response.setHeader("Content-disposition","attachment; filename=check.xlsx"); // Used to name the download file and its format

     File my_file = new File("E://outputtext.xlsx"); // We are downloading .xlsx file, in the format of doc with name check - check.xlsx


     OutputStream out = response.getOutputStream();
     FileInputStream in = new FileInputStream(my_file);
     byte[] buffer = new byte[4096];
     int length;
     while ((length = in.read(buffer)) > 0){
        out.write(buffer, 0, length);
     }
     in.close();
     out.flush();
}
0
votes

I guess since the flush() is invoked in the consective step . It is not working properly.

Try to use finally block to flush..