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

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

问题描述

我有一个复杂的对象参数,我需要将它作为帖子发送,因为它对于查询字符串来说可能太长了.后期调用要求动态生成一个 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 POSTing 实现文件下载的方式:

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[^;=
]*=((['"]).*?2|[^;
]*)/,
            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) => {
    // ...
});

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

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