如何从Webapi使用axios.post下载文件 [英] How to download files using axios.post from webapi

查看:280
本文介绍了如何从Webapi使用axios.post下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复杂的对象参数,我需要作为帖子发送,因为它对于查询字符串可能太长了.邮寄电话要求动态生成一个excel文件,然后异步下载.但是所有这些都是在React应用程序内部发生的.如何使用axios.post,react和webapi做到这一点?我已经确认该文件确实会生成,并且下载到该响应的文件确实会回来,但是我不确定如何实际打开该文件.我有一个隐藏的iframe,试图将文件的路径src设置为该路径,但我不知道要使用哪个响应属性.

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.');
    });

推荐答案

这是我通过Axios通过POST实现文件下载的方式:

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

这篇关于如何从Webapi使用axios.post下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆