Roj Beraña Roj Beraña - 5 months ago 154
AngularJS Question

download csv file from web api in angular js

my API controller is returning a csv file as seen below:

public HttpResponseMessage GenerateCSV(FieldParameters fieldParams)
var output = new byte[] { };
if (fieldParams!= null)
using (var stream = new MemoryStream())
this.SerializeSetting(fieldParams, stream);
output = stream.ToArray();
var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(output) };
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
FileName = "File.csv"
return result;

and my angularjs that will send and receive the csv file is shown below:

$ = function () {
var csvInput= extractDetails();

// File is an angular resource. We call its save method here which
// accesses the api above which should return the content of csv, function (content) {
var dataUrl = 'data:text/csv;utf-8,' + encodeURI(content);
var hiddenElement = document.createElement('a');
hiddenElement.setAttribute('href', dataUrl);;

In chrome, it downloads a file which is called
but has no file type extension.
The content of the file is
[Object object]

In IE10, nothing is downloaded.

What could i do to fix this?

This might work for you guys out there with the same problem: link


Try it like :, function (content) {
    var hiddenElement = document.createElement('a');

    hiddenElement.href = 'data:attachment/csv,' + encodeURI(content); = '_blank'; = 'myFile.csv';;

based on the most excellent answer in this question