3

I want to try download image click on button, but when I click on button so that is not downloads image but it is directly opens image but i want do download image so how to download image in reactjs ?

<a
  href="https://timesofindia.indiatimes.com/thumb/msid-70238371,imgsize-89579,width-400,resizemode-4/70238371.jpg"
  download
 >
   <i className="fa fa-download" />
 </a>
Dharmesh
  • 4,415
  • 16
  • 39
  • 60

4 Answers4

12

Came across this SO trying to figure out how to download a png image and found that the other answer didn't quite do it for me as the downloaded file couldn't be opened. Needed to use arraybuffer to convert the image.

Here's the code that worked.

function App() {
  const download = e => {
    console.log(e.target.href);
    fetch(e.target.href, {
      method: "GET",
      headers: {}
    })
      .then(response => {
        response.arrayBuffer().then(function(buffer) {
          const url = window.URL.createObjectURL(new Blob([buffer]));
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", "image.png"); //or any other extension
          document.body.appendChild(link);
          link.click();
        });
      })
      .catch(err => {
        console.log(err);
      });
  };
  return (
    <div className="App">
      <a
        href="https://upload.wikimedia.org/wikipedia/en/6/6b/Hello_Web_Series_%28Wordmark%29_Logo.png"
        download
        onClick={e => download(e)}
      >
        <i className="fa fa-download" />
        download
      </a>
    </div>
  );
}

Codesandbox: https://codesandbox.io/s/dreamy-gould-h1l72

P.S. The download approach was taken from, this reply, but used plain fetch instead of axios. https://stackoverflow.com/a/50220546/10006323

alanmynah
  • 131
  • 1
  • 9
8

Install file-saver package:

npm i file-saver

Your react component:

  import { saveAs } from 'file-saver'

  const Index = () => {
    const downloadImage = () => {
      saveAs('image_url', 'image.jpg') // Put your image url here.
    }

    return <Button onClick={downloadImage}>Download!</Button>
  }
Michael Eakins
  • 4,139
  • 3
  • 32
  • 54
Ibad Shaikh
  • 1,245
  • 1
  • 11
  • 18
7

You can do something like this :

function App() {
  const download = () => {
    var element = document.createElement("a");
    var file = new Blob(
      [
        "https://timesofindia.indiatimes.com/thumb/msid-70238371,imgsize-89579,width-400,resizemode-4/70238371.jpg"
      ],
      { type: "image/*" }
    );
    element.href = URL.createObjectURL(file);
    element.download = "image.jpg";
    element.click();
  };
  return (
    <div className="App">
      <a
        href="https://timesofindia.indiatimes.com/thumb/msid-70238371,imgsize-89579,width-400,resizemode-4/70238371.jpg"
        download
        onClick={() => download()}
      >
        <i className="fa fa-download" />
        download
      </a>
    </div>
  );
}

Here is working url : https://codesandbox.io/s/clever-noether-3nu2p?fontsize=14

Note : More things can be done. I have just created this for demo purpose

Shubham Verma
  • 4,389
  • 1
  • 7
  • 21
1

Here is an example to download an image with a URL and dynamic name.

const download = async() => {
 const originalImage="https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-512.png";
 const image = await fetch(originalImage);

 //Split image name
 const nameSplit=originalImage.split("/");
 const  duplicateName=nameSplit.pop();

 const imageBlog = await image.blob()
 const imageURL = URL.createObjectURL(imageBlog)
 const link = document.createElement('a')
 link.href = imageURL;
 link.download = ""+duplicateName+"";
 document.body.appendChild(link)
 link.click()
 document.body.removeChild(link)  
};
Rohit Agrohia
  • 200
  • 3
  • 6