3
我试图从MVC 5控制器流式输出,并且无法使浏览器(IE 10,11,Chrome)识别出 输出流和管道到Excel。我已通过将输出保存到 文件并打开它来验证该流是有效的Excel文件。我已经使用Fiddler来确定标题和数据看起来没问题(见下文)。控制器是 由下面列出的jquery ajax调用调用。下面列出了所调用的Controller方法。 ajax返回状态返回错误函数,req.status = 200(OK),但status ='parseerror'。 任何帮助,将不胜感激。将excel文件从MVC 5控制器流式传输到浏览器
$.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");
}
提琴手输出:
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调用接收的所有数据,所以我现在不知道如何做到用参数调用控制器。
根据http://stackoverflow.com/questions/5061310/jquery-returning-parsererror-for-ajax-request你说jQuery的你期望类型JSON的结果然后你正在返回一个文件,你应该删除行dataType:'json' – 2015-04-03 14:41:44
是的,但这不是我想要的行为。我希望将ajax调用重定向到控制器,而控制器又会生成一个流出到浏览器的文件。如果有一个可以用参数调用控制器的ajax调用,那也是可以接受的。 – 2015-04-03 14:51:52
如果你真的需要它是一个POST我相信你可以在你的页面上创建一个表单,而不是进行ajax调用,你可以改变那个表单上的字段并通过JQuery提交它,你将从服务器获取文件办法。如果它可以是一个GET,你可以改变你的窗口的位置,并将下载文件。 – 2015-04-03 15:02:15