I have React.js and Node.js application. In that application I need to download image from URL like normal download which stores image in browser’s downloads.
I have tried many methods from frontend (React) as well as backend (node.js by calling api to save image).
Unfortunately most of solution opening image in new tab, some downloading file in unsupported format.
I tried like following code samples from React
1.
<a href="https://help.twitter.com/content/dam/help-twitter/brand/logo.png" download="https://help.twitter.com/content/dam/help-twitter/brand/logo.png"> Download Here </a>
- Using Link
Link to="https://help.twitter.com/content/dam/help-twitter/brand/logo.png" target="_blank" download>Download</Link
3.
const downloadFile = (
filePath,
fileName = 'myimg.png',
) => {
fetch('https://cors-anywhere.herokuapp.com/' + filePath, {
method: 'GET',
headers: {
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment',
},
})
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement('a');
link.href = url;
link.download = fileName;
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
});
};
<button
onClick={() => downloadFile('https://help.twitter.com/content/dam/help-twitter/brand/logo.png')}
>
Download my image
</button>
- Tried with
js-file-download
package
Above methods and some other solutions are not working as expected.
Please help to download image from url in browser’s download
Thanks
3
Answers
To download an image to a local system using an anchor () tag and a URL in a React component, you can create a link with the href attribute pointing to the image URL, and set the download attribute to specify the desired filename.
As of late 2018, clicking the link won’t trigger a download if the resource to be downloaded wasn’t served from the same origin or same server. Apparently, this is restriction is a security measure.
It would be help to you.
In this modified version:
I removed the Content-Type and Content-Disposition headers, as they are typically set by the server.
I added a .catch block to handle errors during the fetch process.
Please note that the use of https://cors-anywhere.herokuapp.com/ might not be necessary if the server hosting the file supports CORS. If CORS is an issue, you may need to handle the file download on the server side or use a proxy server.