Home >Web Front-end >JS Tutorial >How to use the front end to download base64 images (code)

How to use the front end to download base64 images (code)

不言
不言Original
2018-09-14 15:59:265283browse

The content of this article is about how to use the front-end to implement base64 image download (code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Background

During the project development process, there is often a need to export images, especially for applications with charts, which usually require downloading and exporting charts.
It is relatively easy to download base64 images in new browsers such as Chrome:

  1. Create an a tag

  2. Place a The href attribute of the tag is assigned the base64 encoding of the image

  3. Specifies the download attribute of the a tag as the name of the downloaded file

  4. triggers the a tag Click event

But this set of logic does not work under IE, and writing this way will directly report an error.
So IE needs to be processed separately. Here IE provides a separate method when processing this kind of file: window.navigator.msSaveOrOpenBlob(blob, download_filename). Calling this method can directly trigger the download of IE, which is more convenient. of. The specific method is as follows:

// 截取base64的数据内容(去掉前面的描述信息,类似这样的一段:data:image/png;base64,)并解码为2进制数据
var bstr = atob(imgUrl.split(',')[1]) 
// 获取解码后的二进制数据的长度,用于后面创建二进制数据容器
var n = bstr.length 
// 创建一个Uint8Array类型的数组以存放二进制数据
var u8arr = new Uint8Array(n) 
// 将二进制数据存入Uint8Array类型的数组中
while (n--) {
  u8arr[n] = bstr.charCodeAt(n) 
}
// 创建blob对象
var blob = new Blob([u8arr])
// 调用浏览器的方法,调起IE的下载流程
window.navigator.msSaveOrOpenBlob(blob, 'chart-download' + '.' + 'png')

Overall implementation code

  // 这里是获取到的图片base64编码,这里只是个例子哈,要自行编码图片替换这里才能测试看到效果
  const imgUrl = 'data:image/png;base64,...'
  // 如果浏览器支持msSaveOrOpenBlob方法(也就是使用IE浏览器的时候),那么调用该方法去下载图片
  if (window.navigator.msSaveOrOpenBlob) {
    var bstr = atob(imgUrl.split(',')[1])
    var n = bstr.length
    var u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    var blob = new Blob([u8arr])
    window.navigator.msSaveOrOpenBlob(blob, 'chart-download' + '.' + 'png')
  } else {
    // 这里就按照chrome等新版浏览器来处理
    const a = document.createElement('a')
    a.href = imgUrl
    a.setAttribute('download', 'chart-download')
    a.click()
  }

Related recommendations:

php base64-based decoded image and encrypted image restoration example,

The above is the detailed content of How to use the front end to download base64 images (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn