So, I'm trying to download the file with ajax. The file is downloaded but the user only knows of the file after clicking it is when the file is saved to disk. When I open the network tab, I can see that the xhr is downloading the content.
I'm using ember in the front-end.
How could I make it possible that it downloads directly to the file disk?
The backend is Java and it return InputStream.
I use ajax because there are some authorization headers in the request.
$.ajax(assign({
dataType: 'blob',
processData: false,
success: (data, textStatus, jqXHR) => {
// this.saveFileAs(filename, data, jqXHR.getResponseHeader('Content-Type'));
console.log(filename);
let filenamee = '';
const disposition = jqXHR.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = filenameRegex.exec(disposition);
console.log(matches);
if (matches != null && matches[1]) filenamee = matches[1].replace(/['"]/g, '');
}
const type = jqXHR.getResponseHeader('Content-Type');
const blob = new Blob([data], {
type: type
});
const URl = window.URL || window.webkitURL;
const downloadUrl = URL.createObjectURL(blob);
console.log(downloadUrl);
console.log(filenamee);
if (filenamee) {
const 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); // cleanup
},
error: (jqXHR, textStatus, errorThrown) => {
console.warn('Couldnt download');
},
}, requestSettings));
Aucun commentaire:
Enregistrer un commentaire