Reputation: 77
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
Upvotes: 0
Views: 1759
Reputation: 11
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());
Upvotes: 1
Reputation: 11
I guess since the flush() is invoked in the consective step . It is not working properly.
Try to use finally block to flush..
Upvotes: 0
Reputation: 72
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();
}
Upvotes: 0