How to download files using axios.post from webapi

后端 未结 1 524
伪装坚强ぢ
伪装坚强ぢ 2021-01-21 09:12

I have a complex object parameter that I need to send as post, as it could be too long for querystring. The post call is asking to have an excel file dynamically generated and t

相关标签:
1条回答
  • 2021-01-21 09:28

    This is how I've achieved file downloads by POSTing via Axios:

    Axios.post("YOUR API URI", {
        // include your additional POSTed data here
        responseType: "blob"
    }).then((response) => {
        let blob = new Blob([response.data], { type: extractContentType(response) }),
            downloadUrl = window.URL.createObjectURL(blob),
            filename = "",
            disposition = response.headers["content-disposition"];
    
        if (disposition && disposition.indexOf("attachment") !== -1) {
            let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/,
                matches = filenameRegex.exec(disposition);
    
            if (matches != null && matches[1]) {
                filename = matches[1].replace(/['"]/g, "");
            }
        }
    
        let a = document.createElement("a");
        if (typeof a.download === "undefined") {
            window.location.href = downloadUrl;
        } else {
            a.href = downloadUrl;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
        }
    }).catch((error) => {
        // ...
    });
    
    0 讨论(0)
提交回复
热议问题