1、echarts图表不使用工具栏控件,直接下载
(我这里页面上有多个图表,所以使用了循环)
export() { for (let i = 0; i < 5; i++) { const canvas = document.getElementsByTagName('canvas')[i] let image = canvas.toDataURL({ type: 'png', pixelRatio: 2, backgroundColor: 'white' }) let a = document.createElement('a') a.href = image a.download = `echarts图表${i + 1}` //文件名 console.log(`文件流`, a.href) //输出文件流 a.click() } },
复制
2、拿到echarts图表的文件流后,上传服务器供后端使用
exportBtn() { for (let i = 0; i < 1; i++) { const canvas = document.getElementsByTagName('canvas')[i] let image = canvas.toDataURL({ type: 'png', pixelRatio: 2, backgroundColor: 'white' }) console.log(`第${i + 1}个文件流`, image) //输出文件流,传输到后端接口的数据 let file_ = this.base64ToFile(image, '图表名称') let fileData = new FormData() // new formData对象 fileData.append('file', file_) //我这里直接将图片上传服务器了,根据自身需要处理 this.axios.post('/mongodb/fileInfo/uploadFile', fileData).then((res) => { console.log('返回的文件信息', res) }) } }, // base64图片转file文件 base64ToFile(base64, fileName) { // 将base64文件流按照 , 分割前缀与后续内容 let data = base64.split(',') // 获取文件格式(image/png、image/jpeg、image/webp等) let fileType = data[0].match(/:(.*?);/)[1] // 获取后缀(png、jpeg、webp) let suffix = fileType.split('/')[1] // 使用atob()对base64数据进行解码 返回文件数据流 const bstr = window.atob(data[1]) // 获取解码后 文件数据流的长度 let n = bstr.length // 根据解码后数据流的长度创建一个等长的整形数字数组 // 但在创建时 所有元素初始值都为 0 const u8arr = new Uint8Array(n) // 将整形数组的每个元素填充为解码结果字符串对应位置字符的UTF-16 编码单元 while (n--) { // charCodeAt():获取给定索引处字符对应的 UTF-16 代码单元 u8arr[n] = bstr.charCodeAt(n) } // 创建File文件对象 // new File(bits, name, options) const file = new File([u8arr], `${fileName}.${suffix}`, { type: fileType }) // 将返回File文件对象 return file }
复制