vue3 后台返回的接口数据,下载图片到本地
<el-table>
<el-table-column align="left" label="操作" min-width="240">
<template #default="scope">
<el-button icon="edit" type="primary" link @click="editApiFunc1(scope.row)">编辑</el-button>
<el-button icon="delete" type="primary" link @click="deleteApiFunc1(scope.row)">删除</el-button>
<el-button id="dataTocopy" icon="DocumentCopy" type="primary" link @click="copyApiFunc1(scope.row)">一键复制</el-button>
<el-button id="uploadimage" icon="Download" type="primary" link @click="uploadimage1(scope.row)">下载原图</el-button>
</template>
</el-table-column>
</el-table>
<script setup>
import { ref } from 'vue'
// 下载原图
const uploadimage1 = (row) => {
console.log(row, '点击当前行的数据')
console.log(row.init_images, '后端返回的图片')
//下载图片地址和图片名
let image = new Image()
// 解决跨域 Canvas 污染问题
image.setAttribute('crossOrigin', 'anonymous')
let names = 'image' + row.init_images.split('/').pop()
console.log(names, 'names')
image.onload = function () {
let canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
let context = canvas.getContext('2d')
context.drawImage(image, 0, 0, image.width, image.height)
let url = canvas.toDataURL('image/png') //得到图片的base64编码数据
let a = document.createElement('a') // 生成一个a元素
let event = new MouseEvent('click') // 创建一个单击事件
a.download = names || 'photo' // 设置图片名称
a.href = url // 将生成的URL设置为a.href属性
a.dispatchEvent(event) // 触发a的单击事件
}
image.src = row.init_images
}
</script>
效果: