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
download = "name the file here"; document. body. appendChild(a); a. click();
Let's start the steps. Steps 1: Installation - Firstly we will need to install the below npm command in your project. Steps 2: Import AngularCsv - Import AngularCsv in your component file where you want to add your download button to export your csv file. //Your data for download in csv file.
Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited). Note: The different formats support different feature sets.
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
I used the below solution and it worked for me.
if (window.navigator.msSaveOrOpenBlob) { var blob = new Blob([decodeURIComponent(encodeURI(result.data))], { type: "text/csv;charset=utf-8;" }); navigator.msSaveBlob(blob, 'filename.csv'); } else { var a = document.createElement('a'); a.href = 'data:attachment/csv;charset=utf-8,' + encodeURI(result.data); a.target = '_blank'; a.download = 'filename.csv'; document.body.appendChild(a); a.click(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With