gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:25:53 24 4
gpt4 key购买 nike

我正在尝试流式传输来自 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com