vue-cli+axios实现文件上传下载功能(下载接收后台返回文件流)
vue-cli+axios实现附件上传下载记录:
上传:
这里用formData格式传递参数;请求成功后后台返回上传文件的对应信息。
重点是下载:
##############
downloadfile(res){
varblob=newBlob([res.data],{type:'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'});//application/vnd.openxmlformats-officedocument.wordprocessingml.document这里表示doc类型
varcontentDisposition=res.headers['content-disposition'];//从response的headers中获取filename,后端response.setHeader("Content-disposition","attachment;filename=xxxx.docx")设置的文件名;
varpatt=newRegExp("filename=([^;]+\\.[^\\.;]+);*");
varresult=patt.exec(contentDisposition);
varfilename=result[1];
vardownloadElement=document.createElement('a');
varhref=window.URL.createObjectURL(blob);//创建下载的链接
varreg=/^["](.*)["]$/g;
downloadElement.style.display='none';
downloadElement.href=href;
downloadElement.download=decodeURI(filename.replace(reg,"$1"));//下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click();//点击下载
document.body.removeChild(downloadElement);//下载完成移除元素
window.URL.revokeObjectURL(href);//释放掉blob对象
}
##########################
使用blob接收文件流,中间varreg=/^["](.*)["]$/g;为了解决下载的文件前后有_问题,把两侧的""去掉可正常显示;
decodeURI():对后台返回的中文文件名url编码进行转码
PS:下面看下VUE+axios上传文件,下载文件中的一个坑。
问题描述:最近一个项目中使用axios进行上传和下载,但是上传和下载是需要定义responseType和headers的,这样问题就出来了当你没有权限时候这个接口是抛出一个json数据的,同样上传格式错误也是一个json数据的;由于已经定义了responseType所以接到的数据是已经被转换的数据,它同样会进行下载这时候就需要我们判断返回数据时候的headers是否为文件以外的定义,然后将blob数据转化为json数据即可。代码如下
下载文件为例:
letrequsetFile=(params,baseurl,url)=>{
axios({
method:'get',
baseURL:baseurl,
url:url,
headers:{'Content-Type':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'},//定义相应头
responseType:'blob',//定义
data:params.query||{}
})
.then(function(res){
params.success&¶ms.success(res)
})
.catch(function(error){
params.error&¶ms.error(error)
})
}
//下面为判断headers和转化blob为json
api.Templet({
success:res=>{
constisEXCLE=res.headers["content-type"]===("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"||"application/vnd.ms-excel");
if(!isEXCLE){
letreader=newFileReader();
reader.onload=e=>this.$message.error(JSON.parse(e.target.result).msg);
reader.readAsText(res.data);
}else{
letblob=newBlob([res.data],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
constfileName=`模板文件${Date.parse(newDate())}.xlsx`;
if('download'indocument.createElement('a')){//非IE下载
constelink=document.createElement('a');
elink.download=fileName;
elink.style.display='none';
elink.href=URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href);//释放URL对象
document.body.removeChild(elink);
}else{//IE10+下载
navigator.msSaveBlob(blob,fileName);
}
}
}
})
总结
以上所述是小编给大家介绍的vue-cli+axios实现文件上传下载功能(下载接收后台返回文件流),希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短