如何通过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?

查看:528
本文介绍了如何通过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天全站免登陆