post請求下載文件,獲取Content-Disposition文件名


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM