在第一次写导出/下载word、excel的时候你是否也是一脸懵?
今天具体记录一下导出改怎么写。
一般的话后端会要求你以json格式(JSON.stringify)传一些列表 id 或其他的字段。然后请求头里也许会让你规定内容类型,我这里为json格式,headers:{ 'content-type':'application/json' }。
后端会返回给你一些编码,类似这种:
怎样对这些编码进行处理呢?
可以对数据类型进行处理,我这里使用的是blob格式,有好几种感兴趣可以搜一下('arryaybuffer'、'document'、'json'、'stream'、'text'),我就不过多介绍了。
请求成功的,打印出来的数据
然后呢,就是编写代码啦。
wordonclick(){
//以我的导出word文档为例
doneaWord(JSON.stringify({prodid:this.idlist})).then(res =>{
if(res.status == 200 ){
//这一行是拿到文件名称,也可以自己命名 let filename = '导出word文档.docx' 要注意后缀
//decodeURL是解码方法 把filename 解码为中文
let filename = decodeURL(res.headers['content-disposition'].split('filename='[1])
//这里的type为word 表格为:application/msexcel
let blob = new Blob([res.data],{type:'application/msword'})
let objecturl = URL.createObjectURL(blob)
let link = document.createElement('a')
link.href = objecturl
link.setAttribute('download',filename);
document.body.appendchild(link)
// 自执行点击事件
link.click();
document.body.removeChild(link)
}
})
}
大致流程就是这些,如果有疑问欢迎私信,看完的同学记得点赞哦!