Vue3 ts 下载base64图片,兼容浏览器同源策略

447 阅读1分钟

vue3点击下载图片的实现

同源策略:非base64图片保存,会存在跨域,后端返回base64格式进行保存图片操作

<script setup lang="ts">
import { ref } from 'vue'
// 下载图片到本地vue3-ts
//base64前缀
const prefixBase64 = 'data:image/png;base64,'
const base64 = 'iVBORw0KGgoAAAANSUhEUgAAAu4A…TE2iFMkQz0B1DmcTJVvp/TZmac9lQxp4AAAAASUVORK5CYII='
const handleDownloadQrIMg = () => {
  // 这里是获取到的图片base64编码
  const imgUrl = prefixBase64 + base64
  // 如果浏览器支持msSaveOrOpenBlob方法(也就是使用IE浏览器的时候),那么调用该方法去下载图片
  if (window.navigator.msSaveOrOpenBlob) {
    let bstr = atob(imgUrl.split(',')[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    let blob = new Blob([u8arr])
    window.navigator.msSaveOrOpenBlob(blob, 'chart-download' + '.' + 'png')
  } else {
    // 这里就按照chrome等新版浏览器来处理
    let a = document.createElement('a')
    a.href = imgUrl
    a.setAttribute('download', 'chart-download')
    a.click()
  }
}
</script>

<template>
  <div class="main">
    <el-image class="img" :src="prefixBase64 + base64" lazy />
    <el-button type="primary" @click="handleDownloadQrIMg" class="btn-w">保存</el-button>
  </div>
</template>