【问题标题】:Download image button下载图像按钮
【发布时间】:2023-01-18 17:51:04
【问题描述】:

在任何浏览器中,如果您看到图像,可以右键单击它并单击“另存为”以下载它。

我正在尝试制作一个按钮来下载图像

下载按钮应该下载上面的图像,条形码。

我正在使用反应,不确定这是否与答案有关。

我读到您可以将 <a/> 标记与 download 属性一起使用,但是,我在 Firefox 上,它将我重定向到托管条形码图像的页面,而不是打开下载窗口:

代码非常简单,如下所示:

<a href='https://barcode.tec-it.com/barcode.ashx?data=${product.barcode}&code=&multiplebarcodes=true&backcolor=%23ffffff&quietzone=10&quietunit=Px&size=Small' download>click me</a>

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    为此,您可以使用URL 中的createObjectURL 静态方法为图像创建下载链接。然后,我们在变量中创建临时 <a> 以编程方式打开该链接。

    async function downloadImage(imageSrc) {
      const image = await fetch(imageSrc)
      const imageBlob = await image.blob()
      const imageURL = URL.createObjectURL(imageBlob)
    
      const link = document.createElement('a')
      link.href = imageURL
      link.download = 'myimage.jpg'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-16
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 2020-09-20
      • 1970-01-01
      • 2016-01-05
      • 2011-02-07
      • 2011-03-18
      相关资源
      最近更新 更多