VUE后台返回Buffer流,导出文件

首先下载需要用到的插件 js-file-download

npm install js-file-download --save

在导出的组件引入fileDownload

import fileDownload from 'js-file-download'

使用

orderExport(){
    var self = this;
    /*responseType: 'arraybuffer'  设置该值能够改变响应类型 ArrayBuffer对象*/
    this.$axios.post('/export',{id},{ responseType: 'arraybuffer'}).then(result => {
        //实际调用
        var head = result.headers['content-type'];
    /*这里如果导出报错后台返回错误信息为json格式,判断headers为application/json时弹出错误信息*/
        if(head && head.toLowerCase().indexOf('application/json') != -1){
    /*ab2str() 该方法是ArrayBuffer转字符串,该方法文章下方有贴出。*/
    /*由于我们responseType指定相应类型为ArrayBuffer对象,所以我们需要进行转换后再弹出提示*/
            self.ab2str(result.data,function(str){
                var json = JSON.parse(str)
                    self.$message.warning({
                        showClose: true,
                        message: result.msg
                    });
            });
        }else{
            /*从后台响应headers中取出文件名fileName*/
            let fileName = result.headers['content-disposition'].split('=')[1];
            /*fileDownload方法第一个参数为后台响应Buffer流,第二个参数为下载文件名*/
            fileDownload(result.data,decodeURI(fileName));
        }
    })
  },

ArrayBuffer转字符串

ab2str(u,f) {
    var b = new Blob([u]);
    var r = new FileReader();
    r.readAsText(b, 'utf-8');
    r.onload = function (){if(f)f.call(null,r.result)}
},
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容