asp.net - MVC 4 导出到 CSV - 另存为对话框在 Chrome 和 Firefox 中不起作用

标签 asp.net asp.net-mvc-4 http-headers download

我正在尝试使用“打开/保存”选项将 csv 文件导出到用户。

我的问题与 how-to-force-chrome-to-open-an-open-file-dialog-when-downloading-a-file-via-as 类似(它正在 Chrome 和 Firefox 中下载文件),我已尝试使用 @Dev 建议的解决方案,但它不起作用。

我编写的代码如下:-

return File(new System.Text.UTF8Encoding().GetBytes(csvData),
                    "text/csv", filename);

但是,它在 Chrome 中不起作用。默认情况下会下载该文件。

然后谷歌搜索后,我发现 returning-a-file-to-view-download-in-mvc ,我试图做如下的事情:-

var csvData = "hello";// I am filling this variable with ,y values from DB!
    var cd = new System.Net.Mime.ContentDisposition
    {
        // for example foo.bak
        FileName = "test",
        Inline = false,
    };
    Response.AppendHeader("Content-Disposition", 
        cd.ToString());
    return File(new System.Text.UTF8Encoding().GetBytes(csvData),
        "text/csv");

但它仍然在 Chrome 中下载文件。然后我遇到了how-to-display-open-save-dialog-asp-net-mvc-4 ,其中 @JoãoSimões 提及为:-

That is browser dependent. If you set to download automatically to a given folder, the browser will download automatically. Firefox and Chrome are some browsers with this behavior. – João Simões Jan 3 at 13:09

如果上述情况属实,那么我该如何解决我的问题?如何获得打开/保存对话框? 我无法使用打开/保存选项导出 CSV。

编辑 1

我试图做这样的事情(明白 here ):-

public class ExcelResult : ActionResult
    {
        public string FileName { get; set; }
        public string Path { get; set; }
        public string Data { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.Buffer = true;
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.AddHeader("content-disposition", "attachment;     filename=" + FileName);
            context.HttpContext.Response.ContentType = "text/csv";
            context.HttpContext.Response.Write(new System.Text.UTF8Encoding().GetBytes(Data));
        }
    }

和我的 Controller 代码:-

return new ExcelResult
                {
                    FileName = "sample.xls",
                    Path = "",
                    Data = csvData
                };

但它仍在下载 Excel ...

编辑2

尝试使用HttpContext.Current.Response打开Excel

/// <summary>
/// Export CSV 
/// </summary>
/// <returns></returns>
public void DownloadCSV()
{
    try
    {
        var csvData = Session["CSVData"].ToString();


        byte[] getContent = new System.Text.UTF8Encoding().GetBytes(csvData);
        System.Web.HttpContext.Current.Response.ClearContent();
        System.Web.HttpContext.Current.Response.ClearHeaders();
        System.Web.HttpContext.Current.Response.Buffer = true;
        System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        System.Web.HttpContext.Current.Response.AddHeader("Content-Length", getContent.Length.ToString());
        System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + "testing.csv");
        System.Web.HttpContext.Current.Response.BinaryWrite(getContent);
        System.Web.HttpContext.Current.Response.Flush();

    }
    catch (Exception ex)
    {
        HttpResponseMessage message = new HttpResponseMessage()
        {
            Content = new StringContent("Error Exporting Data")
        };

        throw new System.Web.Http.HttpResponseException(message);

    }

}

但是,还是不行!!!

最佳答案

@shubh 你试过吗 How to force Chrome to open an "open file dialog" when downloading a file vía ASP.NET codebehind?第二个解决方案他们将图像放在显示如何在 Chrome 中打开对话框的位置。我有 chrome 版本 30.0.1599.101 m,如果您进入该高级设置,然后向下您会找到上面链接答案中给出的复选框,我认为这将解决您的问题。 如果仍然无法正常工作,则可能是您的浏览器有问题,只需将其更新到最新版本,然后重试。 编辑1: 如果您输入文件扩展名 .xls,那么它将在 excel 中打开 csv,您需要将文件名设置为 FileName = "sample.csv", 然后它将以 csv 格式打开。

Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewtoCSVExport.csv");
Response.Charset = string.Empty;
Response.ContentType = "application/text";

有关更多信息,请查看此 http://surajdeshpande.wordpress.com/2013/09/03/export-gridview-data-to-csv-file-in-asp-net/

关于asp.net - MVC 4 导出到 CSV - 另存为对话框在 Chrome 和 Firefox 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19492556/

相关文章:

c# - 如何使智能感知与 RazorEngine 一起工作?

html - 位置 : Fixed makes div go out of page

c# - asp.net core 中的 TempData 为空

jquery - 如何在javascript/jquery中查询特定字段的验证

asp.net-mvc - 以 Webforms Default.aspx 作为起始页的 ASP.NET MVC4

jquery - ASP.NET MVC 4 Web Api ajax 文件上传

c# - 如何在不解析 C# 中的请求流的情况下根据内容长度拒绝和 HTTP Posts?

HTTP Request\Response Header 语法

c# - IIS 中托管的 WCF 有很多打开的请求,服务速度变慢

google-app-engine - 如何在 Google App Engine Standard Env for Go 中获取 request.RemoteAddr 和 X-AppEngine-Country、Region 等的输出?