如何在不打开图像的情况下从 api 下载图像?

How to download an image from api in react without opening it?

我想创建一个从 api 下载图像的下载按钮,我能够做到这一点,但后来遇到了问题。每当我单击下载按钮时,它都会下载图像,但它也会在该页面中打开图像,从而使其离开主页。我想要它,这样它就不会打开图像只下载图像。

这是我做的

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



<div className="row">
        <div className="col-sm-4 text-center">
          {quote?.map((items) => (
            <div class="card" style={{ width: "18rem;" }}>
              <img src={items.img} class="card-img-top" alt="..." />
              <div class="card-body">
                <h5 style={{ textTransform: "capitalize" }} class="card-title">
                  {items.name.replace(/_/g, " ")}
                </h5>
                <p class="card-text">{items.disc}</p>
                <Button
                  variant="outlined"
                  href={items.img}
                  onClick={ download }
                >
                  Download
                </Button>
              </div>
            </div>
          ))}
        </div>
      </div>

仅当请求的图像 被 CORS 策略阻止时,客户端解决方案才会起作用。

  async function download(url) {
    const a = document.createElement("a");
    a.href = await toDataURL(url);
    a.download = "myImage.png";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }

  function toDataURL(url) {
    return fetch(url)
      .then((response) => {
        return response.blob();
      })
      .then((blob) => {
        return URL.createObjectURL(blob);
      });
  }

  function onClick() {
    download("https://github.githubassets.com/images/modules/profile/badge--acv-64.png");
  }

codesandbox

完成工作演示

如果您有服务器访问权限,您只需添加 Content-disposition header 然后只需执行 window.open(url, '_self') 即可下载图像 -

NGINX - add_header Content-disposition "attachment; filename=";