如何在reactjs中下载图像?

3pmvbmvn  于 2023-01-25  发布在  React
关注(0)|答案(6)|浏览(224)

我想尝试下载图像点击按钮,但当我点击按钮,使不是下载图像,但它是直接打开图像,但我想做下载图像,所以如何在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>
91zkwejq

91zkwejq1#

遇到了这个所以试图找出如何下载一个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>
  );
}

代码和框:https://codesandbox.io/s/dreamy-gould-h1l72
附言:下载方法取自此回复,但使用了普通获取而不是axios.https://stackoverflow.com/a/50220546/10006323

lo8azlld

lo8azlld2#

安装文件保护程序包:

npm i file-saver

您的React组分:

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

1wnzp6jl3#

你可以这样做:

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

下面是工作URL:https://codesandbox.io/s/clever-noether-3nu2p?fontsize=14

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

wgxvkvu94#

下面是一个使用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)  
};
ui7jx7zq

ui7jx7zq5#

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

shyt4zoc

shyt4zoc6#

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

相关问题