c# - 将 excel 文件从 MVC 5 Controller 流式传输到浏览器

标签 c# jquery ajax asp.net-mvc streaming

我正在尝试流式传输来自 MVC 5 Controller 的输出,但无法让浏览器(IE 10,11、Chrome)识别 输出流和管道到 Excel。我已通过将输出保存到来验证该流是有效的 Excel 文件 一个文件并打开它。我已经使用 Fiddler 确定 header 和数据看起来没问题(见下文)。 Controller 是 由下面列出的 jquery ajax 调用调用。正在调用的 Controller 方法也在下面列出。 ajax 返回状态返回到 req.status = 200(OK)的错误函数,但 status = 'parseerror'。 任何帮助将不胜感激。

$.ajax({
    type: "POST",
    url: "http://localhost:42655/Home/Save",
    data: paramdata,
    contentType: defaultjsonformat,
    dataType: 'json',
    success: function(data) {
         alert(data);
    },
    statusCode: {
        404: function (content) { alert('cannot find resource'); },
        500: function (content) { alert('internal server error'); }
    },
    error: function (req, status, errorObj) {
        if (status === "timeout") {
            alert('Timeout');
        } else {
            alert(status);
        }

    }

);

HomeController.cs:

[AcceptVerbs(HttpVerbs.Post)]
public FileStreamResult Save(string document)
{
    document = document.Trim();


    byte[] bytefile = Export.Excel.ProcessExport.ExportFile(document);

    var stream = new MemoryStream(bytefile);

    return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", document + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".xlsx");

}

fiddler 输出:

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 5.2
Content-Disposition: attachment; filename=test2015-04-03-06-52-04.xlsx
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcTFJQXFJvb3QtREVWXFNjZW5hcmlvXFNjZW5hcmlvXEhvbWVcU2F2ZQ==?=
X-Powered-By: ASP.NET
Date: Fri, 03 Apr 2015 13:52:04 GMT
Content-Length: 9779

PK    6 F H  

编辑:我意识到 ajax 调用正在接收所有数据,所以我现在想知道如何使用参数调用 Controller 。

最佳答案

我不认为您将能够通过 jQuery ajax 调用实现您正在寻找的东西。它不是为下载这样的文件而设计的。

我很幸运地使用以下插件实现了与您相同的行为(从 MVC Controller 异步返回 excel 电子表格):https://github.com/johnculviner/jquery.fileDownload .

希望对您有所帮助:)

关于c# - 将 excel 文件从 MVC 5 Controller 流式传输到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29433749/

相关文章:

c# - 从 JavaScript 引用 C# 方法而不调用它

c# - 具有内部实例化的空列表上的扩展方法

javascript - 执行后禁用

jquery - 钻取内的堆叠列 - HighCharts

javascript - 重新加载页面部分时的 AJAX 请求

javascript - 无法根据从 2 个下拉列表中选择的值获取值

c# - 使用 RGB 值设置 Excel 单元格颜色

c# - Java 中 XMLSignature 中的 DigestValue 与 C# 不同

jquery - HTML5 Boilerplate plugins.js 问题

ruby - 为什么使用 AJAX 的 rspec 示例无法正常工作?