Creating a download link with download
attribute not working ?
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.
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:
- Prevent the default behavior of the click event using
e.preventDefault()
. - Get the URL of the image from the
href
attribute of the clicked element. - Extract the filename from the URL using your
GetFileName()
function.
it return the file name from the link - Send a CORS-enabled request to the server hosting the image using the
fetch()
function. - Retrieve the image data as a blob using the
blob()
method of theResponse
object returned byfetch()
. - Create a blob URL using
URL.createObjectURL()
and pass it to yourforceDownload()
function along with the filename.
your HTML
<a href="https://example.com/myfile.pdf" onclick="Download(event);">Download File</a>