鍍金池/ 問答/HTML/ axios請求獲取excel文件,結(jié)果excel里的內(nèi)容是response體的內(nèi)

axios請求獲取excel文件,結(jié)果excel里的內(nèi)容是response體的內(nèi)容

需求是頁面有個(gè)下載功能,下載的目標(biāo)文件是excel文件,我用axios請求接口,請求成功,可以獲取excel文件,但是excel文件里的內(nèi)容不正確,excel里的內(nèi)容是接口返回的響應(yīng)體內(nèi)容,一串長長的字符串,而不是正確的excel內(nèi)容

export function getBlobRequest(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params,
            responseType: 'blob' //返回?cái)?shù)據(jù)的格式,可選值為arraybuffer,blob,document,json,text,stream,默認(rèn)值為json
        })
        .then(response => {
            resolve(response);
        })
        .catch(err => {
            console.log(`接口調(diào)用失敗`);
            Message.error({message: '網(wǎng)絡(luò)異常,請稍后再試!'});
            reject(err);
        })
    })
}

blob解析代碼

if (!data) {
        return;
    }
    let head = data.headers['content-disposition'];
    let type = data.headers['content-type'];
    console.log(type)
    let url = window.URL.createObjectURL(new Blob([data.data], {type: type}));

    let fname = '';
    if (head) {
        try {
            fname = head.split(';')[2].split('=')[1];
            let reg = new RegExp('"',"g");
            fname = fname.replace(reg, "");
        }catch (err){
            console.log('can not get pdf name');
        }

    }

    let link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;
    link.setAttribute('download', fname);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link); //下載完成移除元素
    window.URL.revokeObjectURL(url); //釋放掉blob對象

圖片描述

回答
編輯回答
雨蝶

你請求的是blob,返回的內(nèi)容也沒有錯(cuò)(只要你程序沒有問題)
但是blob 是被瀏覽器加載,默認(rèn)不會(huì)下載到本地的,你要做的就是把這個(gè)blob寫入到本地,直接寫肯定是不行的,因?yàn)闉g覽器安全限制的原因,但還是有變通的辦法的,給一個(gè)小例子

var saveData = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, fileName) {
        var json = JSON.stringify(data),
            blob = new Blob([json], {type: "octet/stream"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());

var data = { x: 42, s: "hello, world", d: new Date() },
    fileName = "my-download.json";

saveData(data, fileName);

以上代碼 構(gòu)建了一個(gè)json文件的blob 并實(shí)現(xiàn)下載,

2018年5月28日 01:00
編輯回答
我以為

剛實(shí)現(xiàn)的需求。 不用form表單,想用ajax實(shí)現(xiàn)下載的話, 百度搜索 js-file-download

2017年3月15日 08:42
編輯回答
奧特蛋

后端返回excel的地址,你下載就行了

2018年3月17日 23:51