3

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 !

1 Answer 1

7

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);
 }
Sign up to request clarification or add additional context in comments.

4 Comments

I see that you switched it from text/csv to application/octet-stream. Is that necessary? Or can you just use a new StringContent() instead of a new StreamContent()
They all eventually convert down to a stream. The StreamContent was used to match the file stream that was opened to get the file data.
ResponseMessage comes under which namespace? I can not find it
@Neel it is a method of the ApiController.ResponseMessage, which is assumed to be used in the OP given the version of Web API being used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.