React.js download image from url

1k Views Asked by At

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>
  1. 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>
  1. 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

2

There are 2 best solutions below

2
kungfuKenny On

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.

const imageUrl = 'https://help.twitter.com/content/dam/help-twitter/brand/logo.png';
const filename = 'image.jpg'; // Specify the desired file name

<a href={imageUrl} download={filename}>
  Click here to download the image
</a>
0
Heller Stern On

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.