如何在reactjs中下载图像? [英] How to download image in reactjs?

查看:57
本文介绍了如何在reactjs中下载图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尝试点击按钮下载图片,但是当我点击按钮时,这不是下载图片而是直接打开图片,但我想下载图片,那么如何在 reactjs 中下载图片?

解决方案

遇到这个 SO 试图弄清楚如何下载 png 图像并发现另一个答案对我来说并不完全,因为下载的文件不能不会被打开.需要使用 arraybuffer 来转换图像.

这是有效的代码.

function App() {const 下载 = e =>{控制台日志(e.target.href);获取(e.target.href,{方法:获取",标头:{}}).then(响应 => {response.arrayBuffer().then(function(buffer) {const url = window.URL.createObjectURL(new Blob([buffer]));const link = document.createElement("a");链接.href = url;link.setAttribute("下载", "image.png");//或任何其他扩展document.body.appendChild(link);链接.点击();});}).catch(错误 => {控制台日志(错误);});};返回 (<div className="应用程序">下载(e)}><i className="fa fa-download"/>下载</a>

);}

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

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

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>

解决方案

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

这篇关于如何在reactjs中下载图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆