gpt4 book ai didi

c# - 从 asp.net web api 下载文件

转载 作者:行者123 更新时间:2023-11-30 13:35:50 26 4
gpt4 key购买 nike

我正在尝试从 asp.net web api 下载文件 (.docx)。

因为我已经在服务器中有一个文件,所以我将路径设置为现有文件,然后我按照 stackoverflow 上的建议执行此操作:

docDestination 是我的路径。

   HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(docDestination, FileMode.Open, FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
return result;

在那之后,在我的客户端,我尝试这样做:

    .then(response => {
console.log("here lives the response:", response);
var headers = response.headers;
var blob = new Blob([response.body], { type: headers['application/vnd.openxmlformats-officedocument.wordprocessingml.document'] });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "Filename";
link.click();
}

这是我收到的回复

response

我得到的:

what i get

有什么帮助吗?

最佳答案

只需将 ContentDisposition 添加到您的响应 header 中,其值为 attachment,浏览器会将其解释为需要下载的文件

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(docDestination, FileMode.Open,FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "document.docx"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
return result;

看看this linkContentDisposition header

中获取更多信息

关于c# - 从 asp.net web api 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45639599/

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