Reputation: 774
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>
Upvotes: 5
Views: 31361
Reputation: 11
Try this my code, using javascript and html
https://codepen.io/irfanzidan09/pen/XWWmYjN?editors=1111
dont forget add
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Upvotes: 0
Reputation: 6895
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
Upvotes: 10
Reputation: 774
It is working fine for me, maybe it will work for you if you try it like this by creating the link in javascript
var link = document.createElement('a');
link.textContent = 'download image';
link.addEventListener('click', function(ev) {
link.href = "https://www.w3schools.com/html/pic_trulli.jpg";
link.download = "image.jpg";
}, false);
document.body.appendChild(link);
<HTML>
<Header>
</Header>
<body>
</body>
</HTML>
Upvotes: 1
Reputation: 11
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
Upvotes: 1
Reputation: 502
<a id="download_image" href="" download="https://docs.google.com/uc?id=0B0jH18Lft7ypSmRjdWg1c082Y2M" download>Download 1</a>
Upvotes: -1