下载文件接口封装

101 阅读1分钟
一.引入axios配置axios
import axios from axios;
const withTokenAxios = axios.create();

withTokenAxios.defaults = {
  ...withTokenAxios.defaults,
  'Content-Type': 'application/json; charset-utf-8',
  'Accept': 'application/json'
}

// Add a request interceptor
withTokenAxios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return {
      ...config,
      url: '', // 配置对应环境请求地址
      headers: {
        ...config.headers,
        Authorizations: '',
        'H-request-id': '',
       // ...
      }
    };
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
withTokenAxios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    const { status, data } = response;
    if(status == 200 || status == 204){
      return response;
    }
    // 根据项目接口自定义返回拦截
    if(data || data.failed) {
      throw response;
    }else{
      return response;
    }
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

二.请求文件接口将文件流生成为blog地址,挂载到a链接
// params 调用参数
// params.requestUrl 文件请求地址
// params.queryParams 文件请求参数
// params.methods 请求方法
// params.queryData 请求数据
export function downFile(params, fileName){
  const { requestUrl, queryParams,methods, queryData } = params;
  const API_HOST = ''; //主机地址
  const newUrl = `${API_HOST}${requestUrl}`; //当前环境域名
  if(queryParams && Array.isArray(queryParams)){
    newUrl += '?';
    queryParams.forEach((item,index) => {
      if(index===0){
        newUrl += `${item.name}=${encodeURIComponent(item.value)}`
      }else{
        newUrl += `&${item.name}=${encodeURIComponent(item.value)}`
      }
    })
  }
  return withTokenAxios(
    {
      url: newUrl,
      methods,
      baseUrl: API_HOST,//域名地址
      responseType:'arraybuffer',
      //data: queryData, 当methods不为GET时候可传
    }
  ).then(res => {
    const {data, headers} = res
    let fileNameNew = fileNaNewme ? fileName : window.decodeURI(headers['content-dispositon'].split('=')[1],'UTF-8');
    // 处理返回结果,将二进制文件流转换成blob
    let blob = new Blob([data],  {type: 'application/octet-stream;charset=UTF-8'});
    let fileURL = window.URL.creatObjectURL(blob);
    const downLoadFile = document.createElement('a');
    downLoadFile.display = 'none';
    downLoadFile.href = fileURL;
    downLoadFile.download = fileNameNew;//文件名
    document.body.appendChild(downLoadFile);
    downLoadFile.click();
    document.body.removeChild(downLoadFile);
    window.Url.revokeObjectUrl(fileURL); // 释放blob对象
  })
}

三.业务组件中调用

// requestUrl文件请求地址
// queryParams上传文件参数
downFile({
    requestUrl: '',
    queryParams: [
        {name:'bucketName',value:'桶名'},
        {name:'url',value:'文件url地址'}
    ]
})