JavaScript can't download images programmatically (getting 403)

1.6k views Asked by At

In my website I've a button that whenever user clicks on it downloads him a random image, here is the code to download an image:

const downloadImg = (src) => {
    const imgName = src.replace(/^.*[\\\/]/, '');

    var a = document.createElement('a');
    a.href = src;
    a.download = imgName;
    a.click();
};

This works completely fine from images that are from open websites, like google.com or Wikipedia commons

However, for images from websites like Pixabay, Pexels, Freepik instead of downloading the Image it opens the image URL in the same tab and gives me 403 forbidden error in the console

I completely understand why this error happens, but what I don't understand is how to fix it? If I right-clicked on the image then hit save image as no error will appear and I will be able to download the image normally, how can I do this with javascript programmatically?

2

There are 2 answers

3
Igor Moraru On

It works using the approach from accepted answer here: Chrome 65 blocks cross-origin <a download>. Client-side workaround to force download? , with a minor change. Instead of using mode "cors" use "no-cors". Apparently there is a cors error with some domains when downloading directly from url.

Updated: It does not work if the server does not allow cros-origin requests. Making the request with "no-cors" will succeed, but the response body will not be available. So this is NOT a solution.

0
Edwin Tigor On

You can use javascript fetch to download the random selected image from url address.

Code:

JS:
<script>
function downloadImage(url, name){
  fetch(url)
    .then(resp => resp.blob())
    .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        // the filename you want
        a.download = name;
        document.body.appendChild(a);
        a.click();
        //window.URL.revokeObjectURL(url);
    })
    .catch(() => alert('An error sorry'));}</script>

HTML:<button onclick="downloadimage('https://pixabay.com/get/g2cc1f3e1fe58926edc20db6cf67be6dd1614d93b06e934118288e4c57d5228c60c50de32506ac83ffdabc6fe20a6a01b3c7504b82965e6043e9038185180f3ae_1920.jpg', 'download.jpg')" >download</button>

example: https://viena.lovestoblog.com/bakDownload/bak.php