axios请求service, csv文件下载

前言

请求库:基于axios。
服务器:返回csv文件

(一) 重置request.js 通用请求库

const BASE_URL = process.env.REACT_APP_BASE_API;

const instance = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
});

instance.interceptors.request.use(config => {
  ...
  return config;
});

instance.interceptors.response.use(response => {
  const { data, status } = response;
  if ((status >= 200 && status < 300) || status === 304) {
     // responseType handle arraybuffer
    if (Object.is('arraybuffer', response.config.responseType)) {
      const filename = response.headers['content-disposition'] || '';
      return { filename, file: data };
    }
    // other handle
    return data;
  }
  const res = new Error(data.code);
  res.response = response;
  throw res;
}, (err) => {
  ...
  ...
});

export default instance;

export function getBufferResType(download) {
  return download ? 'arraybuffer' : 'json';
}

(二) 封装api请求url

import axios, { getBufferResType } from '@/utils/request';

// download is 1, start
export function getMinerPayoutList({
  download = 0,
}) {
  return axios.get(`/miners/payouts`, {
   // must be setting response type, 
    responseType: getBufferResType(download),
    params: {
      download,
    },
  });
}

(三) 封装文件处理

/**
   * https://github.com/mholt/PapaParse/issues/175
   * @params options
   * {
   *   file ArrayBuffer 文件
   *   filename 文件名
   * }
   */
  downloadCSVFile({ file, filename = 'filename' }) {
    const blob = new Blob([file]);
    // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
    const result = filename.split(';filename=')[1];
    if (result && result.endsWith('.csv')) {
      filename = result;
    } else {
      filename = `${result || filename}.csv`;
    }
    if (window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveBlob(blob, filename);
    } else {
      const a = window.document.createElement('a');
      a.href = window.URL.createObjectURL(blob, { type: 'text/plain' });
      a.download = filename;
      document.body.appendChild(a);
      // IE: "Access is denied"; see: https://connect.microsoft.com/IE/feedback/details/797361/ie-10-treats-blob-url-as-cross-origin-and-denies-access
      a.click();
      document.body.removeChild(a);
    }
  },

(四) 后台增加返回header(axios header才拿得到content-disposition)

Access-Control-Expose-Headers: Content-Disposition

(五) 调用api

import { getMinerEarningsList } from '@/api/miners';
import Base from '@/utils/base';

...
...
// saga
const fetchOrderSaga = function* saga({ payload = {} }) {
  try {
    const result = yield call(getMinerEarningsList, {
      ...payload,
    });
    if (payload.download) {
      Base.downloadCSVFile(result);
      yield put({
        type: Types.FETCH_ORDER_RESPONSE,
        payload: {},
      });
      return false;
    }
    const { data: list = [], page_size, page_index, total: page_total, extra_data = {} } = result;
    yield put({
      type: Types.FETCH_ORDER_RESPONSE,
      payload: { ...payload, list, page_size, page_index, page_total, extra_data },
    });
  } catch (e) {
    yield put({
      type: Types.FETCH_ORDER_RESPONSE,
      payload: { errMsg: e.message },
    });
  }
};

你可能感兴趣的:(React,JS工具类)