5

I am trying Export csv file to the User with Open/Save option.

My issue is some what similar to how-to-force-chrome-to-open-an-open-file-dialog-when-downloading-a-file-via-as(It is downloading the file in Chrome and Firefox), I have tried with the solution suggested by @Dev but it is not working.

I wrote my code as below:-

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

But, it was not working in Chrome. The file is getting downloaded by default.

Then after googling , I found returning-a-file-to-view-download-in-mvc, from which I was trying to do something like below:-

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");

but still it was downloading the file in Chrome. then I came across how-to-display-open-save-dialog-asp-net-mvc-4, where @JoãoSimões mentioned as:-

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

If the above is true, then how can I overcome my problem? How can I get the open/save dialogue ? I am unable to Export my CSV with open/save option.

Edit 1

I was trying to do something like this (got it 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));
        }
    }

and My controller code:-

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

but still, it is downloading the Excel ...

Edit 2

Tried opening the excel with HttpContext.Current.Response

/// <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);

    }

}

but, still not working!!!

Community
  • 1
  • 1
Shubh
  • 6,693
  • 9
  • 48
  • 83
  • Does the open/save dialogue appear when you download an csv/xls file form any other page like [this](http://www.andrewpatton.com/countrylist.csv) ? If not, it's probably not of your code but with the browser settings. – developer10214 Oct 27 '13 at 09:37
  • @developer10214:- The link you have posted, I am getting dialogue box. I guess then either its my code issues or some alien attack!!! I am still scratching head.. – Shubh Oct 28 '13 at 05:56
  • You code is perfectly fine. It depends on browser settings. There is no way to get around this and you cannot/shouldn't try to override user's browser settings as it would be like hacking the machine. – Poornima Oct 29 '13 at 20:44
  • What do you mean by it is still downloading? Chrome, Safari & Firefox will download file straight to downloads folder. It will not ask for Save dialog unless user right click on the link & click Save Link as. Another option would be to use File API. – Akash Kava Oct 31 '13 at 07:31
  • @AkashKava - True! I got that point. But there should have been something which would allow us to override that feature. Or in other words what @Poornima said, `I wanted to override browser settings.` and as per her Hack it! – Shubh Nov 11 '13 at 07:25
  • @ShubhDasgupta I told you, it's HTML5 File API which allows you to ask user for Save As location from JavaScript. – Akash Kava Nov 11 '13 at 09:17

3 Answers3

2

@shubh have you tried How to force Chrome to open an "open file dialog" when downloading a file vía ASP.NET codebehind? second solution they have put image in where they show how to open dialog box in chrome. I have chrome Version 30.0.1599.101 m in that if you go to setting in that advance setting then down you will find check box which was given in above link answer, that will solve your problem I think. If still not working then might be problem with your browser just update it to latest version then try again. Edit 1: If you put your file name extension .xls then it will open in excel for csv you need to put file name as FileName = "sample.csv", then it will open in csv format.

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

for more check this http://surajdeshpande.wordpress.com/2013/09/03/export-gridview-data-to-csv-file-in-asp-net/

Community
  • 1
  • 1
  • Yes, I have tried that. I tried it 2 days back when `@developer10214` suggested that it may be browser issue!! But, it was not working. I have even uninstalled chrome and installed it back... :( – Shubh Oct 30 '13 at 06:41
  • I uninstalled and installed my chrome, to have the latest version as it was not updating. But didn't work out. I just tried with hard-coding file name, but no result. Lets see, I have contacted my network team, if they have done something fishy. grrrr... Thanks for your suggestions satish! Really appreciate. – Shubh Oct 30 '13 at 06:52
  • Try to add this code and check it might be working `Response.Output.Write(getContent.ToString()); Response.Flush(); Response.End();` – Satish ratnaparkhi Oct 30 '13 at 07:02
  • It may be late. But after a lot of effort I was not able to get it. Thanks to my superiors who understood the problem. Your link was helpful to make the understand [**how-to-force-chrome-to-open-an-open-file-dialog**](http://stackoverflow.com/questions/13933531/how-to-force-chrome-to-open-an-open-file-dialog-when-downloading-a-file-via-as). Thanks for your efforts +1. Will request you to update your answer highlighting the link :) – Shubh Apr 24 '14 at 11:32
1

If the user has configured his browser to automatically download files, there's absolutely nothing you could do on the server to force this dialog to appear. I am afraid that what you are trying to achieve is impossible.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • You may be right! After scratching my head for more than 9 days, I also feel the same. Let me see, if I can find any alternative solution for that. Thanks! – Shubh Oct 30 '13 at 09:02
0

Try to supply another value for your content-disposition header:

Response.AppendHeader("Content-Disposition", "attachment");
Community
  • 1
  • 1
m1kael
  • 2,801
  • 1
  • 15
  • 14