I am facing difficulties in downloading an Excel file using Ajax. I came across this code on another website and implemented it in my project:
$.ajax({
type: "POST",
url: "myStrutsAction.action",
data: {p1:p1, p2:p2},
success: function(response, status, xhr){
disableMyLoadingUserPopupScreen();
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
disposition);
}
var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
var a = document.createElement("a");
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100);
}
}
});
This script helps prompt the user to save or open the specific Excel file. However, when trying to open the file, it appears damaged with unreadable characters in Notepad++:
Below is my Struts2 execute method on the server:
public String execute(){
// Create Excel File
returnFileAsStream("myExcelfile");
return null;
}
In this method, I set the HTTP Response Header as follows:
private void returnFileAsStream(final String filename) throws IOException {
final InputStream is = new FileInputStream(filename);
OutputStream os = null;
try {
response.setContentType("application/octet-stream");
response.setHeader("Cache-Control", "maxage=3600");
response.setHeader("Pragma", "public");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
os = response.getOutputStream();
int length;
byte buf[] = new byte[1024];
while ((length = is.read(buf)) > 0) {
os.write(buf, 0, length);
}
is.close();
os.close();
} finally {
// additional code here
}
}
Could it be that handling file downloads with Ajax is not feasible? Perhaps the issue lies in trying to manage binary data with Ajax, which may not fully support binary operations?