Roj Beraña Roj Beraña - 2 months ago 89
AngularJS Question

download csv file from web api in angular js

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

[HttpPost]
public HttpResponseMessage GenerateCSV(FieldParameters fieldParams)
{
var output = new byte[] { };
if (fieldParams!= null)
{
using (var stream = new MemoryStream())
{
this.SerializeSetting(fieldParams, stream);
stream.Flush();
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:

$scope.save = 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
File.save(csvInput, function (content) {
var dataUrl = 'data:text/csv;utf-8,' + encodeURI(content);
var hiddenElement = document.createElement('a');
hiddenElement.setAttribute('href', dataUrl);
hiddenElement.click();
});
};


In chrome, it downloads a file which is called
document
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?

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

Answer

Try it like :

File.save(csvInput, function (content) {
    var hiddenElement = document.createElement('a');

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

based on the most excellent answer in this question

Comments