ASP.NET MVC下载提示不出现
我正在尝试在控制器操作中生成一个Excel .xlsx文件。 我想让网站显示下载提示下载结果文件。 控制器操作执行正常,但不显示下载提示。 什么都没发生。
我试过了:
MemoryStream mstream = ... //generated file; return File(mstream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", model.DisplayName + ".xlsx");
我试过了:
return new FileStreamResult(mstream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = model.DisplayName + ".xlsx" };
我试过了:
Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; filename=" + model.DisplayName + ".xlsx"); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.Write(mstream.ToArray()); Response.End(); return Content("");
我甚至尝试将文件保存到磁盘,然后通过文件path返回
return File(filepath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
我究竟做错了什么? 谢谢!
我在MVC项目中使用下面的代码。
public ActionResult GetCSV() { string filename = "example"; string csv = MyHelper.GetCSVString(); return File(Encoding.UTF8.GetBytes(csv.ToString()), "text/csv", string.Format("{0}.csv", filename)); }
我的csvstring可能看起来像这样
"Col1,Col2,Col3\nRow1Val1,Row1Val2,Row1Val3\n"
要在新窗口中触发此下载,请调用以下JavaScript
window.open('/MyUrl/GetCSV', 'DownloadWindowName');
添加标题如下。
var cd = new System.Net.Mime.ContentDisposition { FileName = model.DisplayName + ".xlsx", Inline = false }; Response.AppendHeader("Content-Disposition", cd.ToString());
然后如下返回文件
return File(mstream, ".xlsx");
关于下载提示。 如果您的意思是询问保存文件的位置,则取决于用户如何在浏览器设置中进行设置。 例如,在Chrome中,用户可以select在下载文件时不会得到提示,并将其下载到预先指定的位置,如下载文件夹。 http://malektips.com/google-chrome-prompt-download-file.html#.VM-DbFWsUm8