1.写一个公用的函数,并export出去
data表示后端接口返回的res.data
name表示后端接口返回表格的名称
export function downloadBlob(data, name) {
const blob = new Blob([data], { type: 'application/vnd.ms-excel' }) //构造一个blob对象来处理数据
//对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
//IE10以上支持blob但是依然不支持download
if ('download' in document.createElement('a')) {
//支持a标签download的浏览器
const link = document.createElement('a') //创建a标签
link.download = name //a标签添加属性
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.click() //执行下载
URL.revokeObjectURL(link.href) //释放url
document.body.removeChild(link) //释放标签
} else {
//其他浏览器
navigator.msSaveBlob(blob, name)
}}
2.在要用的页面引入上面的方法
import { downloadBlob } from '@/utils/index'
3.请求后端给的下载接口,这边的$http对axios做了封装
fileName指的是文件名称
this.$http({
url: {
key: ' ',
url: ' '
},
method: 'post',
responseType: 'arraybuffer',//前端请求二进制数据的时候需要设置数据响应格式;
data: {
fileName
}
}).then(res => {
//当请求成功,应用封装的函数
downloadBlob(res.data, fileName)
})
释:responseType: 'arraybuffer'
前端请求二进制数据
的时候需要设置数据响应格式;
通过对应数据类型的请求,可以得到二进制数据,数据被存储在通过ArrayBuffer这个构造函数创建一个缓冲区内,取得数据后需要使用相对应的[TypedArray(https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/TypedArray)进行解析。
responseType可选的参数有:"text"、"arraybuffer"、"blob"或"document";对应的返回数据为DOMString、ArrayBuffer、Blob、Document;默认参数为"text"。
释:type: 'application/vnd.ms-excel'
获取请求返回的response对象中的blob 设置文件类型,并将输出文件类型为excel文件。
context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + context.Server.UrlEncode("Excel名称") + ".xls");//设置文件名称
context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
context.Response.ContentType = "application/vnd.ms-excel";//设置输出文件类型为excel文件。