React.js 从 url 下载图片

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

我有 React.js 和 Node.js 应用程序。在该应用程序中,我需要像普通下载一样从 URL 下载图像,它将图像存储在浏览器的下载中。

我尝试了前端(React)和后端(node.js 通过调用 api 保存图像)的许多方法。 不幸的是,大多数解决方案在新选项卡中打开图像,有些以不受支持的格式下载文件。

我尝试遵循 React 的代码示例

1.

<a href="https://help.twitter.com/content/dam/help-twitter/brand/logo.png" download="https://help.twitter.com/content/dam/help-twitter/brand/logo.png"> Download Here </a>
  1. 使用链接

链接到=“https://help.twitter.com/content/dam/help-twitter/brand/logo.png”target=“_blank”下载>下载

3.

const downloadFile = (
  filePath,
  fileName = 'myimg.png',
) => {
  fetch('https://cors-anywhere.herokuapp.com/' + filePath, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/octet-stream',
      'Content-Disposition': 'attachment',
    },
  })
    .then(response => response.blob())
    .then(blob => {
      const url = window.URL.createObjectURL(new Blob([blob]));

      const link = document.createElement('a');
      link.href = url;
      link.download = fileName;

      document.body.appendChild(link);

      link.click();

      link.parentNode.removeChild(link);
    });
};

<button
        onClick={() => downloadFile('https://help.twitter.com/content/dam/help-twitter/brand/logo.png')}
      >
        Download my image
      </button>
  1. 尝试过
    js-file-download

上述方法和其他一些解决方案未按预期工作。

请帮忙从浏览器下载地址下载图片 谢谢

javascript reactjs image download imagedownload
2个回答
0
投票

要在React组件中使用anchor()标签和URL将图像下载到本地系统,您可以创建一个href属性指向图像URL的链接,并设置download属性以指定所需的文件名。

const imageUrl = 'https://help.twitter.com/content/dam/help-twitter/brand/logo.png';
const filename = 'image.jpg'; // Specify the desired file name

<a href={imageUrl} download={filename}>
  Click here to download the image
</a>

0
投票

截至 2018 年末,如果要下载的资源不是来自同一来源或同一服务器,则单击链接将不会触发下载。显然,这是一种安全措施。

对你会有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.