Question

I am using MVC 4.

I have a method in my controller which generates a CSV file on demand and I want this file to be then downloaded by the user without the need of saving it to the disk at the server side. So I am passing a MemoryStream on the File() object to avoid having to firstly save file to disk and later give him the path for download.

Controller Method:

[HttpGet]
public ActionResult GenerateCsv(string data)


    var sb = new StringBuilder();
    sb = GetCsvReportToString(data);

    var stream = new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString()));

    return this.File(stream, "text/csv", "ReportCsv.csv");
}

sb (StringBuilder) has the correct data, as I have debugged it and confirmed it.

my javascript code:

window.open(generateFileLink + '?data=' + dataToSend, '_blank');

The window gets in fact opened, the download dialog appears but with an error, saying that it cannot be downloaded from localhost:

enter image description here

The name is different in the download "ReportToCsv" because I didn't use real names for methods in my question, but doesn't matter.

Can anyone assist?

Was it helpful?

Solution 2

The answer to this question can be found here: https://stackoverflow.com/a/11267754/1417487

It's a regarding the headers of cache, for IE versions 6-8.

OTHER TIPS

Try this

var sb = new StringBuilder();
            sb=GetCsvReportToString(data);
            return File(Encoding.UTF8.GetBytes(sb.ToString()), System.Net.Mime.MediaTypeNames.Application.Octet, "ReportCsv.csv");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top