Reputation: 3200
I am trying to download a csv file using web api 2 and angular js.
This is my controller code
public IHttpActionResult ExportCsvData()
{
var stream = new FileStream("Testcsv.csv", FileMode.Open, FileAccess.Read);
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Testcsv.csv"
};
return Ok(response);
}
This is my angular code,
var filename = 'testcsv.csv';
var contentType = 'text/csv;charset=utf-8';
var blob = new Blob([data], { type: contentType });
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, filename);
}
I am using IE 11, but when I open the file in excel, it looks like this,
{ "version": {
"major": 1
"minor": 1
"build": -1
"revision": -1
"majorRevision": -1
"minorRevision": -1 } "content": {
"headers": [
{
"key": "Content-Type"
"value": [
"application/octet-stream"
]
}
{
"key": "Content-Disposition"
"value": [
"attachment; filename=testcsv.csv"
]
}
]
What am I doing wrong?
Thanks !
Upvotes: 3
Views: 8885
Reputation: 247591
You need to return a response message. The Ok()
will serialize the HttpResponseMessage as is.
public IHttpActionResult ExportCsvData()
{
var stream = new FileStream("Testcsv.csv", FileMode.Open, FileAccess.Read);
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Testcsv.csv"
};
return ResponseMessage(response);
}
Upvotes: 7