问题
I've created excel file using Apache POI and tried to return it as response to ajax call. I want the browser to prompt "save the created file" window. The problem is that I get gibbrish in the servlet's response and no prompts or whatsoever
I've found similar problems here, on StackOverflow, but the solutions to their issues doesn't work for me (or I miss something).
Here the problem was solved by using html tags, but I can't (as far as I know) use them in SAPUI5.
And here is a very similar case, which I used for my matter, but it still doesn't work.
Here is the client side code:
jQuery.ajax({
url : "Export",
type : "post",
mimeType: 'application/vnd.ms-excel',
success : function(){
console.log("data was exported successfully");
},
error: function(){
console.log("error while exporting data");
},
complete: function(){
console.log("exporting data has been completed");
}
});
And here is the servlet's code:
response.setContentType("application/vnd.ms-excel");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setHeader("Content-Disposition", "attachment; filename=ReportsData.xls");
ServletOutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
The file is created from a database 'select' wuery result set in a while(result.next())
loop.
Thank you!
回答1:
Instead of using ajax try making a call like this in javascript.
window.open(("urltoyourservlet"), "_blank");
This will open a new window linking directly to your servlet. Then the browser should automatically handle handle downloading the excel file based on the mime/type.
来源:https://stackoverflow.com/questions/26342891/return-excel-file-created-in-servlet-as-response