Jquery 如何强制从ASP.NET WebAPI下载文件

Jquery 如何强制从ASP.NET WebAPI下载文件,jquery,asp.net,asp.net-mvc,rest,asp.net-web-api,Jquery,Asp.net,Asp.net Mvc,Rest,Asp.net Web Api,这是我的web api代码: [HttpPost] public HttpResponseMessage PostFileAsAttachment() { string path = "D:\\heroAccent.png"; if (File.Exists(path)) { HttpResponseMessage result = new HttpResponseMessage(HttpStatu

这是我的web api代码:

    [HttpPost]
    public HttpResponseMessage PostFileAsAttachment()
    {
        string path = "D:\\heroAccent.png";
        if (File.Exists(path))
        {

            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            var stream = new FileStream(path, FileMode.Open);
            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = "xx.png";
            return result;
        }
        return new HttpResponseMessage(HttpStatusCode.NotFound);
    }

以及如何对客户端(视图)进行编码以强制下载文件(如自动下载模式(打开、另存为)可以弹出…)

文件可用的ActionResult类型之一是FileResult 如果要传输的内容存储在磁盘文件中,则可以使用FilePathResult对象。如果您的内容通过流可用,则使用FileStreamResult,如果可以作为字节数组使用,则选择FileContentResult。所有这些对象都派生自FileResult,它们之间的区别仅在于它们将数据写入响应流的方式

例:PDF格式

public FileResult Export()
{
var output = new MemoryStream();
    :
    return File(output.ToArray(), "application/pdf", "MyFile.pdf");
}
请查找下面的链接,了解如何使用Ajax Jquery调用操作方法

您可以参考这篇文章,它可以让您对文件结果有一些了解


如上所述,您不能从ajax触发“打开/另存为”对话框

如果您想在下载文件时保留当前页面内容,您可以在页面中的某个位置添加一个隐藏的iframe,并让您的下载链接在后台执行一些JS操作,以将所述iframe的src属性设置到适当的位置

$('iframeSelector').attr('src', downloadLinkLocation)

我已经用一个返回FileContentResult的操作对此进行了测试,但是如果您在响应标题中设置ContentDisposition,那么我看不出有什么理由不能与WebAPI方法一起工作。

您的意思是想在下载文件之前显示Open,Save as popup吗?是的..我想使用jquery ajax方法,但在HttpResponseMessage返回后,您可以使用
window.location
导航到此下载url,或者使用javascript中的
window.open()
打开一个新窗口。你不能用ajax下载文件,我正面临着这个问题。您找到解决方案了吗?我不想使用mvc操作,我只想通过客户端直接调用web api方法,比如:$.ajax({url:'',键入:“post”,contentType:“application/json”,data:“”,success:function(retData){*****}我只是不知道如何处理ajax success函数中的retData参数以弹出下载窗口