I have already passed through some of the suggested solutions here in SO, but with no success. This is the problem. When the blob is generated using the data retrieved from the API endpoint, I want to force browser to download the blob. I have tried three solutions so far, but no of them works. Code follows. Notice that I put some comments in the code to explain further.
const FILE_NAME_REGEX = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
export function Download(url) {
return APICall.get(url).then(response => {
const disposition = response.request.getResponseHeader('Content-Disposition');
//^This line gives the 'Refused to get unsafe header "Content-Disposition"' error, so next few lines won't execute and part with generating anchor is not used, but the part of code under the 'else' branch.
if (disposition && disposition.indexOf('attachment') !== -1) {
const matches = FILE_NAME_REGEX.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, '');
}
}
const type = response.request.getResponseHeader('Content-Type');
const blob = new Blob([response.data], { type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
const URL = window.URL || window.webkitURL;
const downloadUrl = URL.createObjectURL(blob);
if (filename) {
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();
document.body.removeChild(a);
}
} else {
// 1. soultion
window.location = downloadUrl;
}
setTimeout(() => {
URL.revokeObjectURL(downloadUrl);
}, 100);
}
});
}
// 2. solution
const ifrmDownloader = document.createElement('iframe');
ifrmDownloader.setAttribute('src', downloadUrl);
ifrmDownloader.style.width = '0px';
ifrmDownloader.style.height = '0px';
document.body.appendChild(ifrmDownloader);
// 3. solution
window.open(downloadUrl,_blank);
Solution does not work because it opens another tab and returns empty little square instead of the file. This is probably due to the lost temp blob when new tab got opened.
Solution simply does not work, and I do not know why. Iframe gets added to the dom and request is recorded in the Network tab under developer console, but no download is trigerred. Probably the same reason as in the solution 1. In addition this message is logged:
Resource interpreted as Document but transferred with MIME type image/png: "blob:https://example.com/e53bf47b-7f39-4758-b3dd-3cc2df5889ad".
- Solution does not work as well. First of, browser blocked pop up, and after te pop up is allowed, no file download is initiated.
I feel that something is missing here, but what?