美文网首页
js调接口实现文件下载功能(请求头添加token)

js调接口实现文件下载功能(请求头添加token)

作者: zhenghongmo | 来源:发表于2019-11-28 16:14 被阅读0次
    • GET请求
     function createObjectURL(object) { return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object); }
                    var xhr = new XMLHttpRequest();
                    var formData = new FormData();
                    xhr.open('get',`api/org/sku/purchase/month/statement?startTime=${startTime}&endTime=${endTime}&export=true`);  //url填写后台的接口地址,如果是post,在formData append参数(参考原文地址)
                    xhr.setRequestHeader("token", localStorage.getItem('token'));
                    xhr.responseType = 'blob';
                    xhr.onload = function (e) {
                        if (this.status == 200) {
                            var blob = this.response;
                            var filename = `采购统计-${year}(按月度统计).xls`;  
                            console.log(this.response)
                             if (window.navigator.msSaveOrOpenBlob) {
                                navigator.msSaveBlob(blob, filename);
                            } else {
                              var a = document.createElement('a');
                             var url = createObjectURL(blob);
                             a.href = url;
                             a.download = filename;
                             document.body.appendChild(a);
                             a.click();
                             window.URL.revokeObjectURL(url);
                            }
                            
                        }
                    };
                    xhr.send(formData);
    
    • POST请求
    function createObjectURL(object) { return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object); }
                                         var xhr = new XMLHttpRequest();
                                        //  var formData = new FormData();
                                         xhr.open('post',`api/tc/login/list?export=true`);  //url填写后台的接口地址,如果是post,在formData append参数(参考原文地址)
                                         xhr.setRequestHeader("token", localStorage.getItem('token'));
                                         xhr.setRequestHeader("Content-Type", 'application/json;charset=UTF-8');
                                         xhr.responseType = 'blob';
                                         xhr.onload = function (e) {
                                             if (this.status == 200) {
                                                 var blob = this.response;
                                                 var filename = `成员列表.xls`;  
                                                 console.log(this.response)
                                                  if (window.navigator.msSaveOrOpenBlob) {
                                                     navigator.msSaveBlob(blob, filename);
                                                 } else {
                                                   var a = document.createElement('a');
                                                  var url = createObjectURL(blob);
                                                  a.href = url;
                                                  a.download = filename;
                                                  document.body.appendChild(a);
                                                  a.click();
                                                  window.URL.revokeObjectURL(url);
                                                 }
                                                 
                                             }
                                         };
                                         xhr.send(JSON.stringify({
                                            searchLike: name,
                                            roleId: roleId, 
                                            pageSize: pageSize,
                                            pageNo:currents,
                                        }));
                                        
    

    axios请求

    • 封装axios请求 (添加:responseType: 'blob',)
    import axios from 'axios';
    import {message} from 'antd';
    import qs from 'qs';
    import Util from '@/utils/util';
    import UtilsForm from '@/utils/form';
    
    const {API_SERVER} = $G.server;
    const source = $G.source;
    let { app_key, ENV } = $G.server;
    ENV = ENV[source];
    const urlKeys = Util.urlKeys();
    const lsg = window.localStorage;
    app_key = app_key[$G.type];
    
    // axios 中文使用说明
    // https://www.kancloud.cn/yunye/axios/234845
    const jsonAxios = axios.create({
      baseURL: API_SERVER,
      timeout: 600000,
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json',
        'Accept': '*/*',
        'app-key': app_key,
        'env': ENV,
        'lang': 'cn-zh',
        'user-secret': window.localStorage.getItem('user-secret'),
      },
      // 在传递给 then/catch 前,允许修改响应数据
      // 通过Qs.stringify转换为表单查询参数
      // transformRequest: [(data) => {
      //   data = qs.stringify(data);
      //   return data;
      // }],
      // 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。
      // 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`) ,
      // promise 将被 resolve; 否则,promise 将被 rejecte 。
      validateStatus: status => status === 200,
    });
    
    // 表示跨域请求时是否需要使用凭证
    // 设置请求允许携带cookie
    // jsonAxios.defaults.withCredentials = true;
    
    // 响应拦截
    jsonAxios.interceptors.response.use((res = {}) => {
      if(res.data.code === "ERR_API_0004") {
        message.error("未登录或登录过期!");
        // window.location.href="/login";
        return;
      }
      return Promise.resolve(res.data);
    });
    
    const blobRequest = {
    
      urlParams(token) {
        let R = {
          ...urlKeys,
          app_key,
          token,
          env:ENV,
          timestamp: new Date().getTime(),
        };
    
        R = qs.stringify(R);
        jsonAxios.defaults.headers['user-secret'] = window.localStorage.getItem('user-secret');
    
        return R;
      },
    
      async post(url, data, isLogin=true) {
    
        // 防止抖动
        if(!Util.debounce(url)) throw `请求{${url}}操作频繁`;
    
        let token = lsg.getItem('token');
    
        // if(isLogin === true) {
        //   if(!token) {
        //     return await {};
        //   }
        // }
    
        const urlParams = this.urlParams(token);
    
        // 过滤数据
        data = UtilsForm.formToJson(data, true);
        
        let symbol = '?';
        if(url.split('?').length > 1) {
          symbol = '&';
        }
    
        const awaitData = await jsonAxios.post(`${url}${symbol}${urlParams}`, data);
        Util.debounce(url, true);
    
        return awaitData;
      },
    
      async get(url, data) {
        data = UtilsForm.formToJson(data, true);
        return await jsonAxios.post(`${url}`, {params:data});
      },
    }
    
    export {
      blobRequest
    }
    
    
    • 发起请求,处理blob数据
    blobRequest.post('background/order_flow/v1/export', data).then((res) => {
     const blob = new Blob([res], {type: 'application/vnd.ms-excel;charset=utf-8'});
        const fileName = `平台流水.xls`//下载的文件名称及其后缀,后缀要和后台保持的一致
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName);
        } else {
          var a = document.createElement('a');
          var url = this.createExportXLSURL(blob);
          a.href = url;
          a.download = fileName;
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
        }
      }
    })
    

    对返回json格式的错误进行处理

    getFiles(_path, query) {
        axios({
          method: 'get', // 请求方式
          headers: {
            'Content-Type': 'application/octet-stream',
            'token': store.getters.token
          },
          url: _path, // 请求路径
          params: query,
          responseType: 'blob'
        }).then(res => {
          const data = res.data;
          if (res.data.type == 'application/json') {     // json信息展示
            this.handlerResponseError(data);
          } else {
            // 下载文件流
            const filename = this.getCaption(res.headers['content-disposition']);
            const blob = new Blob([res.data], {
              type: 'application/octet-stream'
            });
            const objectUrl = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = objectUrl;
            link.setAttribute('download', filename);
            document.body.appendChild(link);
            link.click();// 点击
            document.body.removeChild(link); // 下载完成移除元素
            window.URL.revokeObjectURL(URL); // 释放掉blob对象
          }
        }).catch((err) => {
          console.log(err, 'err');
        });
      },
    
      handlerResponseError(data) {
        const _this = this;
        const fileReader = new FileReader();
        fileReader.onload = function() {
          try {
            const jsonData = JSON.parse(fileReader.result); // 说明是普通对象数据,后台转换失败
            console.log('后台返回的信息',jsonData.msg);
           // dosomething……
          } catch (err) { // 解析成对象失败,说明是正常的文件流
            console.log('success...');
          }
        };
        fileReader.readAsText(data);
      },
    

    相关文章

      网友评论

          本文标题:js调接口实现文件下载功能(请求头添加token)

          本文链接:https://www.haomeiwen.com/subject/mdmbwctx.html