使用AXIOS在Firefox扩展中使用XMLHttpRequest获取二进制数据

问题描述 投票:1回答:1

我试图从Firefox浏览器下载二进制数据。我的应用程序基于react和redux并使用axios作为我的HTTP客户端。我必须在xhr.open()之前发送responseType= arraybuffer

下面的实现没有用

 axios({
        url:`http://api.demo6.test.com:8080/resources/v1/${dObj.payload.surveyId}`,
        responseType: 'arraybuffer',
        method: 'post',
        data: dObj.payload.filterData,
        headers: {
            "Accept": "application/vnd.ms-excel",
            "Content-Type": "application/json",
            "X-Bazaarify-Session-Token": "cfff-7-07f13399abed" //token
        }
    }).then(function(response) {
        // const y  = yield put(surveyResponseDowloadComplete({
        //     data: response.data
        // }));
        let blob = new Blob([response.data], {type: "application/vnd.ms-excel"});
        let link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob);
        link.download = "test.xls";
        link.click();
        console.log(response);
        //response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
    });

我怎么能用axios做到这一点?

javascript reactjs redux axios redux-saga
1个回答
1
投票

这是一个使用axios下载二进制数据的简单传奇:

function * downloadFileSaga(url) {
    const response = yield axios.get(url, {
        responseType: 'arraybuffer'
    })
    console.log(response.data); // arraybuffer
}

然后,您可以使用Blob或FileReader进一步使用arraybuffer。

示例:https://codesandbox.io/s/n7kmvjr49m

© www.soinside.com 2019 - 2024. All rights reserved.