I am currently trying to download a PNG file from my Sapui5 application. I have tried several ways, but all of them only displayed the image in a new or the same tab. The download was never triggered.
I have already tried these ways:
1) URLHelper.redirect
2) window.open,
3) window.location.assign,
4) fetch(URL).then(res => res.blob()).then(blob => {
var file = window.URL.createObjectURL(blob);
window.location.assign(file);
5) var link = document.createElement("a");
link.href = FullURL;
link.download = "QRCode.png";
link.target = "_self";
document.body.appendChild(link);
link.click();
document.body.removeChild(link)
6) sap.ui.core.util.File.save
<---- this only results in a file that returns as a message that the file format is probably not supported.
How can I trigger the download?
I am quite new to this and hope you guys can help me. Thanks
CodePudding user response:
Solution #5 only works if the image and the URL have the same origin (protocol, subdomain, domain and port need to be the same).
Exceptions are blob
and data
URLs. So you can combine solution #5 with #4.
I created a small working example.
Relevant code is here:
const sURL = 'https://i.imgur.com/q6E7b9d.png';
fetch(sURL)
.then((oResponse) => oResponse.blob())
.then((oBlob) => {
const sBlobURL = URL.createObjectURL(oBlob);
const oLink = document.createElement('a');
oLink.href = sBlobURL;
oLink.download = sURL.split('/').pop();
oLink.target = '_blank';
document.body.appendChild(oLink);
oLink.click();
document.body.removeChild(oLink);
});
If this also doesn't work then you probably have a CORS issue. Basically the host of your image decides if images can be embedded and downloaded in other pages.