Click to download pictures in vue

The method of clicking to download pictures in Vue can be realized by using the download attribute of the < a > tag in HTML5 or by JS.
The download attribute of the < a > tag can be set directly in html, for example:

<a href="https://example.com/image.jpg" download>下载图片</a>

You can use the method of creating URL objects through JS implementation, the code is as follows:

// 下载图片
   async downloadImage(e) {
    
    
     // 获取图片对象和画布对象
     const imgUrl = https://example.com/image.jpg
     const response = await fetch(imgUrl)
     const blob = await response.blob()
     // 创建下载链接
     const url = window.URL.createObjectURL(blob)
     const link = document.createElement('a')
     link.href = url
     link.download = 'image.png'
     document.body.appendChild(link)
     link.click()
     document.body.removeChild(link)
     // 释放 Blob URL
     window.URL.revokeObjectURL(url)
   }

The above code obtains the image through fetch and converts it into a blob type, then uses URL.createObjectURL to create a download link, implements the download through the click() method of the created < a > tag, and finally removes the newly created < a > tag and the URL object that has been used.

Guess you like

Origin blog.csdn.net/xiaokangna/article/details/130408581