如何通过 Jquery 调用 MVC FileContentResult 并让它提示用户保存它的返回? [英] How can I call an MVC FileContentResult by Jquery and get it to prompt the user to save on it's return?

查看:32
本文介绍了如何通过 Jquery 调用 MVC FileContentResult 并让它提示用户保存它的返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 MVC 3 网站生成 CSV 并使用 FileContentResult 将其传递给用户.这很有效,但生成 csv 需要 30 秒,因此在向用户提示保存之前需要 30 秒.

I'm generating a CSV from an MVC 3 website and using a FileContentResult to pass this to the user. This worked great but it took 30 seconds for the csv to generate and therefore 30 seconds before the prompt to save was given to the user.

    public virtual FileContentResult GetSpreadsheet(string id)
    {
        var service = new SpreadsheetService();
        var result = service.GetCSV();
        return File(new System.Text.UTF8Encoding().GetBytes(result.Message), "text/csv", "Report123.csv");
    }

所以我想我只是通过 JQuery 调用它 - 但这(不出所料!)只是将 CSV 转储到页面.

So I thought I'd just call it via JQuery - but this (unsurprisingly!) just dumps the CSV to the page.

            $.post("/Home/GetSpreadsheet/" + id, null, function (data) {
                $('#resultDiv').html(data);
            });

有谁知道我如何生成提示以保存现在我已经取回了数据?谢谢

Does anyone know how I'd generate the prompt to save now I've got the data back? Thanks

推荐答案

你不能那样做.把它给忘了.使用 AJAX 下载文件是不可能的.实际上,AJAX 调用将起作用,您将访问服务器,服务器将文件内容发送回客户端,将触发 AJAX 成功回调并将文件内容作为参数传递给您,这就是一切结束的地方.使用 javascript,出于绝对明显的原因,您无法将文件直接保存到客户端计算机,也无法提示另存为"对话框.

You can't do that. Forget about that. It is impossible to download files using AJAX. In fact the AJAX call will work, you will hit the server, the server will send the file contents back to the client, the AJAX success callback will be triggered and passed as argument the contents of the file and that's where everything ends for you. Using javascript you cannot, for absolutely obvious reasons, save directly the file to the client computer and you cannot prompt for the Save As dialog.

所以不要使用 AJAX,只需创建一个锚点:

So instead of using AJAX simply create an anchor:

@Html.ActionLink("download spreadsheet", "GetSpreadsheet", new { id = "123" })

现在,如果服务器将 Content-Disposition 标头设置为 attachment,浏览器将提示用户下载文件并将其保存在其计算机上的某个选定位置.

Now if the server set the Content-Disposition header to attachment the browser will prompt the user to download and save the file at some chosen location on his computer.

这篇关于如何通过 Jquery 调用 MVC FileContentResult 并让它提示用户保存它的返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆