javascript 处理来自 JQuery Ajax 的 FileResult

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30661728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:30:31  来源:igfitidea点击:

Handling FileResult from JQuery Ajax

javascriptc#jqueryajaxasp.net-mvc

提问by michael

I have a MVC C# Controller that returns a FileResult

我有一个返回 FileResult 的 MVC C# 控制器

    [HttpPost]
    public FileResult FinaliseQuote(string quote)
    {
        var finalisedQuote = JsonConvert.DeserializeObject<FinalisedQuote>(System.Uri.UnescapeDataString(quote));

        return File(finalisedQuote.ConvertToPdf(), "application/pdf");
    }

Now I want to be able to download the result (I don't want it to open up in the browser) I am calling the controller via $.ajax method in JavaScript

现在我希望能够下载结果(我不希望它在浏览器中打开)我通过 JavaScript 中的 $.ajax 方法调用控制器

var postData = { quote: finalisedQuote };

var url = "/NewQuote/FinaliseQuote";

$.ajax({
    type: "POST",
    url: url,
    data: postData,
    success: function (data) {
        //how do I handle data to force download
    },
    fail: function (msg) {
        alert(msg)
    },
    datatype: "json"
});

How do I handle the data to force it to download?

如何处理数据以强制下载?

回答by Lee Bailey

You won't be able to use JavaScript to save the file to disk as this is blocked for security reasons.

您将无法使用 JavaScript 将文件保存到磁盘,因为出于安全原因,这被阻止了。

An alternative would be to save the file in the FinaliseQuoteaction method (and return just an id for the file), then create another action method that responds to a GET request and returns the file. In your success function you then set window.location.hrefto point to your new action method (you'll need to pass an id for the file). Also make sure you set the MIME type to application/octet-streamand that should force the browser to download the file.

另一种方法是将文件保存在FinaliseQuote操作方法中(并只返回文件的 id),然后创建另一个响应 GET 请求并返回文件的操作方法。在你的成功函数中,你然后设置window.location.href指向你的新操作方法(你需要为文件传递一个 id)。还要确保将 MIME 类型设置为application/octet-stream并且这应该会强制浏览器下载文件。

Controller:

控制器:

[HttpPost]
public JsonResult FinaliseQuote(string quote)
{
    var finalisedQuote = JsonConvert.DeserializeObject<FinalisedQuote>(System.Uri.UnescapeDataString(quote));

    // save the file and return an id...
}

public FileResult DownloadFile(int id)
{
    var fs = System.IO.File.OpenRead(Server.MapPath(string.Format("~/Content/file{0}.pdf", id)));

    // this is needed for IE to save the file instead of opening it
    HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=\"filename\""); 

    return File(fs, "application/octet-stream");
}

JS:

JS:

success: function (data) {
    window.location.href = "/NewQuote/DownloadFile?id=" + data;
},