gpt4 book ai didi

c# - 使用 Jquery Post 使用 Web API 下载文件

转载 作者:行者123 更新时间:2023-11-30 22:05:46 25 4
gpt4 key购买 nike

我有一个返回文件流的 web Api 函数

[HttpPost] 
public HttpResponseMessage DownloadDocument([FromBody] parameters)
{
try
{
var stream = FileHelper.GetFilesStream(fileUrl);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(stream) };
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition.FileName = fileName;
return result;
}
catch (Exception)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "File Not Found");
}
}

如何在 Jquery Ajax 中调用此方法来下载文件,以便弹出保存文件对话框。我正在使用 knockout.js,在按钮的单击事件处理程序中调用此 WebAPI 方法并获取流,但我不知道如何将其保存到文件中。

最佳答案

您无法通过 ajax 调用下载文件。您将需要使用获取请求来下载文件。

你可以做的是像上面那样使用你的 ajax 帖子,但将文件保存在数据库中,然后返回带有文档 ID 的 json 或下载文档的 url。然后您可以添加一个隐藏的 iframe 来下载文档。

看看这个显示如何操作的答案:https://stackoverflow.com/a/16086443/2326610

关于c# - 使用 Jquery Post 使用 Web API 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24186495/

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