Creating a download link with download attribute not working ?

anjit pariyar
2 min readMar 31, 2023

here is an example from w3schools

<a href=”/images/myw3schoolsimage.jpg” download>
<img src=”/images/myw3schoolsimage.jpg” alt=”W3Schools”>
</a>

There could be a few reasons why the download attribute is not working, and here we are talking about when image hosting and your domain are different.

Creating a download link with download attribute not working ?
function to download image from different hosting
function forceDownload(blob, filename) {
var a = document.createElement("a");
a.download = filename;
a.href = blob;
document.body.appendChild(a);
a.click();
a.remove();
}

export const Download = (e) => {
e.preventDefault();
let url = e.target.href;
let name = decodeURI(GetFileName(url).split(".")[0]);
// console.log("name", name);
fetch(url, {
headers: new Headers({
Origin: location.origin,
}),
mode: "cors",
})
.then((response) => response.blob())
.then((blob) => {
let blobUrl = window.URL.createObjectURL(blob);
forceDownload(blobUrl, name);
})
.catch((e) => console.error(e));
};

export const GetFileName = (link: string) => {
let splitLink = link?.split("/");
return splitLink[splitLink.length - 1].slice(0, link.length);
};

Downloading an image from a different hosting domain can be a bit tricky due to the security restrictions enforced by modern browsers. However, we can do it with JS.

In the code, a function forceDownload() that takes a blob and a filename and triggers a download by creating a temporary a element and simulating a click on it. This function can be reused to download images hosted on a different domain.

We can modify Download() function to download the image by following these steps:

  1. Prevent the default behavior of the click event using e.preventDefault().
  2. Get the URL of the image from the href attribute of the clicked element.
  3. Extract the filename from the URL using your GetFileName() function.
    it return the file name from the link
  4. Send a CORS-enabled request to the server hosting the image using the fetch() function.
  5. Retrieve the image data as a blob using the blob() method of the Response object returned by fetch().
  6. Create a blob URL using URL.createObjectURL() and pass it to your forceDownload() function along with the filename.

your HTML

<a href="https://example.com/myfile.pdf" onclick="Download(event);">Download File</a>

--

--