How to download files using axios.post from webapi

时光总嘲笑我的痴心妄想 提交于 2019-12-11 04:59:21

问题


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 then downloaded asynchronously. But all of this is happening inside of a react application. How does one do this using axios.post, react, and webapi? I have confirmed that the file does generate and the download up to the response does come back, but I'm not sure how to actually open the file. I have a hidden iframe that I'm trying to set the path, src, of the file to, but I dont know what response property to use.

// webapi
[HttpPost]
public HttpResponseMessage Post([FromBody]ExcelExportModel pModel)
{
    var lFile = ProductDataModel.GetHoldingsExport(pModel);
    var lResult = new HttpResponseMessage(HttpStatusCode.OK);
    lResult.Content = new ByteArrayContent(lFile);
    lResult.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "HoldingsGridExport.xls"
    };

    lResult.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

    return lResult;
}

// client side api
static getHoldingsExport({ UserConfigurationID, UserID, Configurations, ViewName, SortModel, FilterModel, UserConfigType, IsDefault, LastPortfolioSearchID = null, ProductId }) {
    const filterModel = JSON.stringify(FilterModel); // saving as string as this model is dynamically generated by grid out of my control
    const sortModel = JSON.stringify(SortModel);

    let params = JSON.stringify({
        UserConfigurationID,
        UserID,
        Configurations,
        ViewName,
        filterModel,
        sortModel,
        UserConfigType,
        IsDefault,
        LastPortfolioSearchID,
        ProductId
    });

    return axiosInstance.post("/api/HoldingsExport", params);
}

// client side app call to get file
HoldingsApi.getHoldingsExport(config)
    .then(function(response) {
        debugger;
        let test = response;
    })
    .catch(error => {
        toastr.success('Failed to get export.');
    });

回答1:


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) => {
    // ...
});


来源:https://stackoverflow.com/questions/41949640/how-to-download-files-using-axios-post-from-webapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!