【问题标题】:Making csv file download as instead of opening in browser ASP.NET MVC使 csv 文件下载而不是在浏览器中打开 ASP.NET MVC
【发布时间】:2015-12-24 00:04:45
【问题描述】:

所以我有一个 MVC ASP.NET 项目,在单击按钮时它应该要求用户保存/打开文件。但它的作用是在浏览器中打开文件。该文件是一个 csv 文件。

这是视图的代码

@using (Html.BeginForm("Download", "Home", new { name = ViewBag.Downloadfilename }, FormMethod.Post))
{
<button type="submit">Button 1</button>
 }

虽然控制器的代码是这样的

     public ActionResult Download(string name)
        {

            //string file = @"c:\someFolder\foo.xlsx";
            string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            string file = name;
          return File(file, Path.GetFileName(file));
        }

所以任何人都知道控制器如何强制用户保存文件而不是在浏览器中打开。 (使用铬)。

谢谢

【问题讨论】:

  • 任何您不能使用 Response.Headers 执行此操作的原因...等等 顺便提一下如何简单地在线执行此操作的大量示例..
  • 我查看了它们,但找不到任何与下载相关的内容。有链接吗?
  • 我看到你在哪里创建了一个字符串变量contentType - 但你没有在任何地方使用它。我假设您打算使用该变量作为 Content-Type HTTP 标头的值。
  • Open file in C# 的可能重复项。发帖前请先搜索。您的标题找到了多个匹配项!

标签: c# asp.net asp.net-mvc asp.net-mvc-4 csv


【解决方案1】:
  //Gives me a download prompt.
  return File(document.Data, document.ContentType, document.Name);


 //Opens if it is a known extension type, downloads otherwise (download has      bogus name and missing extension)
 return new FileStreamResult(new MemoryStream(document.Data), document.ContentType);

 //Gives me a download prompt (lose the ability to open by default if known type)
return new FileStreamResult(new MemoryStream(document.Data), document.ContentType) {FileDownloadName = document.Name};

【讨论】:

  • 第一个返回类型中的文档是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
  • 2013-04-17
  • 2019-03-08
  • 2013-10-25
  • 1970-01-01
相关资源
最近更新 更多