gpt4 book ai didi

reactjs - 如何使用 axios.post 从 webapi 下载文件

转载 作者:行者123 更新时间:2023-12-04 02:07:32 25 4
gpt4 key购买 nike

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

// 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 实现文件下载的方式:

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

关于reactjs - 如何使用 axios.post 从 webapi 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41949640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com