如何在 React 中下载图像?

问题描述 投票:0回答:6

我想尝试通过单击按钮来下载图像,但是当我单击按钮时,这不是下载图像,而是直接打开图像。但我想要下载图像,那么如何在 React 中下载图像呢?

<a
  href="https://timesofindia.indiatimes.com/thumb/msid-70238371,imgsize-89579,width-400,resizemode-4/70238371.jpg"
  download
 >
   <i className="fa fa-download" />
 </a>
reactjs image blob
6个回答
20
投票

遇到这个问题,试图找出如何下载 png 图像,发现另一个答案并不适合我,因为下载的文件无法打开。需要使用arraybuffer来转换图像。

这是有效的代码。

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

附注 下载方法取自此回复,但使用普通 fetch 而不是 axios。 https://stackoverflow.com/a/50220546/10006323


17
投票

安装文件保护程序包:

npm i file-saver

你的反应组件:

  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>
  }

8
投票

你可以这样做:

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>
  );
}

这是一个工作网址:https://codesandbox.io/s/clever-noether-3nu2p?fontsize=14

注意:可以做更多的事情。我刚刚创建这个是为了演示目的。


0
投票

这里是下载带有 URL 和动态名称的图像的示例。

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)  
};

0
投票

file-saver 包帮助我们在 Web 应用程序的客户端保存文件。

  • 安装:

    npm i file-saver
    
  • 语法:

    FileSaver.saveAs("https://codemaker2015.github.io/image", "image.jpg");
    
  • 用途:

    import { saveAs } from 'file-saver'
    
    const Main = () => {
        const downloadImage = () => {
            saveAs('image_url', 'image.jpg') // Put your image url here.
        }
    
        return <Button onClick={downloadImage}>Download</Button>
    }
    

了解更多:https://www.npmjs.com/package/file-saver


-1
投票
const Download = () => {
  const [downloadURL, setDownloadURL] = useState("");

  const download = async () => {
    const result = await fetch(fetchURLHere, {
      method: "GET",
      headers: {},
    });
    const blob = await result.blob();
    const url = URL.createObjectURL(blob);
    setDownloadURL(url);
  };

  const handleDownload = async (e) => {
    try {
      await download();
      // Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer.
      URL.revokeObjectURL(downloadURL);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <button onClick={handleDownload} type="button" className="">
      <a href={downloadURL} download={setNameForFile}>
        Download Image
      </a>
    </button>
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.