1、post下载文件代码,doload方法
import request from "../../src/utils/request"; import { API } from "../../constants/API"; import axios from "axios" import { Modal } from "antd"; /** * 生成CSR * @param {*} data */ export function getCsr(data) { return request(API.GET_CSR, { data }); } export function download(url, params, fileName) { return new Promise((resolve, reject) => { axios.post( url, {...params}, {responseType: 'blob'} ) .then(res => { let reader = new FileReader(); let data = res.data; reader.onload = e => { if (e.target.result.indexOf('Result') != -1 && JSON.parse(e.target.result).Result == false) { // 进行错误处理 } else { if (!fileName) { let contentDisposition = res.headers['content-disposition']; if (contentDisposition) { fileName = window.decodeURI(res.headers['content-disposition'].split('=')[1], "UTF-8"); } } executeDownload(data, fileName); } }; reader.readAsText(data); resolve(res.data); }) }); } export function executeDownload(data, fileName) { if (!data) { return } let url = window.URL.createObjectURL(new Blob([data])); let link = document.createElement('a'); link.style.display = 'none'; link.href = url; link.setAttribute('download', fileName); document.body.appendChild(link); link.click(); document.body.removeChild(link); Modal.success({ title: "操作成功", okText:"确定", content: "生成CSR成功!请注意下载文件!", onOk: () => {} }) }
2、如何获取后端传过来的名字,后端需要设置如下:
Access-Control-Expose-Headers : 'Content-Disposition'
3、注意点后台Content-Disposition,需要配合 application/octet- stream