vue-cli + axios实现附件上传下载记录:
上传:
这里用formData格式传递参数,请求成功后后台返回上传文件的对应信息。
重点是下载:
############## downloadfile (res) { var blob=new blob ([res。数据),{类型:“应用程序/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=utf - 8”});//应用程序/vnd.openxmlformats-officedocument.wordprocessingml.document这里表示文档类型 var contentDisposition=res.headers(“附加”);//从响应的标题中获取文件名,后端响应。setHeader(“附加”、“依恋;文件名=xxxx.docx ")设置的文件名; var patt=new RegExp(“文件名=((^;)+ \ \ [^ \ \;]+);*”); var=结果patt.exec (contentDisposition); var文件名=结果[1]; var downloadElement=document.createElement (' a '); var href=https://www.yisu.com/zixun/window.URL.createObjectURL (blob);//创建下载的链接 var reg=/^ [] (. *) ["]/g美元; downloadElement.style。显示='没有'; downloadElement。href=https://www.yisu.com/zixun/href; downloadElement。下载=decodeURI (filename.replace (reg, " $ 1 "));//下载后文件名 document.body.appendChild (downloadElement); downloadElement.click ();//点击下载 document.body.removeChild (downloadElement);//下载完成移除元素 window.URL.revokeObjectURL (href);//释放掉团对象 } # # # # # # # # # # # # # # # # # # # # # # # # # #
使用团接收文件流,中间<代码> var reg=/^ ["] (. *) ["]/g> 代码;美元为了解决下载的文件前后有_问题,把两侧的”“去掉可正常显示;
decodeURI():对后台返回的中文文件名url编码进行转码
问题描述:最近一个项目中使用axios进行上传和下载,但是上传和下载是需要定义responseType和标题的,这样问题就出来了当你没有权限时候这个接口是抛出一个json数据的,同样上传格式错误也是一个json数据的;由于已经定义了responseType所以接到的数据是已经被转换的数据,它同样会进行下载这时候就需要我们判断返回数据时候的头是否为文件以外的定义,然后将团数据转化为json数据即可。代码如下
下载文件为例:
让requsetFile=(params, baseurl, url)=祝辞{ axios ({ 方法:“得到”, baseURL: baseURL, url: url、 标题:{“内容类型”:“应用程序/vnd.openxmlformats-officedocument.spreadsheetml。表的},//定义相应的头 responseType:“blob”//定义 数据:参数。查询| | {} }) 不要犹豫(函数(res) { 参数个数。成功,,params.success (res) }) .catch(函数(错误){ 参数个数。错误,,params.error(错误) }) }//下面为判断头部和转化团为json api.Templet ({ 成功:res=祝辞{ const isEXCLE=res.headers(“内容类型”)===(“应用程序/vnd.openxmlformats-officedocument.spreadsheetml。表“| |”应用程序/vnd.ms-excel”); 如果(! isEXCLE) { 让读者=new FileReader (); 读者。onload=e=比;这个。message.error美元(JSON.parse (e.target.result) .msg); reader.readAsText (res.data); 其他}{ 让blob=new blob ([res。数据),{类型:应用程序/vnd.openxmlformats-officedocument.spreadsheetml.sheet "}); const文件名='模板文件${日期。解析(新日期()}.xlsx '; 如果(“下载”document.createElement (' a ')){//非IE下载 const elink=document.createElement (' a '); elink。下载=文件名; elink.style。显示='没有'; elink。href=https://www.yisu.com/zixun/URL.createObjectURL (blob); document.body.appendChild (elink); elink.click (); URL.revokeObjectURL (elink.href);//释放URL对象 document.body.removeChild (elink); 其他}{//IE10 +下载 导航器。msSaveBlob (blob,文件名); } } } })
以上所述是小编给大家介绍的vue-cli + axios实现文件上传下载功能(下载接收后台返回文件流),希望对大家有所帮助,如果大家有任何疑问欢迎给我留的言,小编会及时回复大家的!