Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download images using HTML or JavaScript

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>
like image 782
Thangakumar D Avatar asked Jan 28 '23 20:01

Thangakumar D


2 Answers

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

like image 25
karl Avatar answered Jan 30 '23 10:01

karl


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

like image 56
Emerica Avatar answered Jan 30 '23 11:01

Emerica