I need to download images from the server. In the below HTML5 code 'Download 1' downloads the image successfully. But 'Download 2' is navigating to the image URL instead of downloading the image. The main difference between 'Download 1' and 'Download 2' is 'Download 2' has file extension as'.jpg' in the file name. I want 'Download 2' to download the image.
I need to download images with the file extension. Please help to resolve the issue. Thanks in advance!
<a id="download_image" href="https://docs.google.com/uc?id=0B0jH18Lft7ypSmRjdWg1c082Y2M" download>Download 1</a>
<a id="download_image" href="https://www.w3schools.com/html/pic_trulli.jpg" download>Download 2</a>
I think it works :
<HTML>
<Header></Header>
<body>
<a id="download_image" href="" download="https://docs.google.com/uc?id=0B0jH18Lft7ypSmRjdWg1c082Y2M">Download 1</a>
<a id="download_image" href="" download="http://serverpath/images/50.jpg">Download 2</a>
</body>
</HTML>
and checkout online demo if you like https://codepen.io/zhipenglu/pen/dKQXQx
and here is another lib do the same thing called file-writer: https://github.com/azl397985856/file-writer
Try the following using Promise and async/await :
toDataURL(url) {
return fetch(url).then((response) => {
return response.blob();
}).then(blob => {
return URL.createObjectURL(blob);
});
}
then
async download() {
const a = document.createElement("a");
a.href = await toDataURL("http://serverpath/images/50.jpg");
a.download = "";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
Find documentation here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With