Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API return csv file

Tags:

I need to get a csv file from web api controller. I can not get "Save As" dialog to show up. Only text output shows up on the page. I tried both, calling Export from jquery and also plain old html

Controller:

[System.Web.Http.HttpGet]
public HttpResponseMessage Export()
{
    StringBuilder sb = new StringBuilder();
    IEnumerable<CustomerDiscount> list = this.subscriberRepository.GetSubscribers();

    foreach (CustomerDiscount item in list)
    {
        sb.AppendFormat(
            "{0};{1};{2};",
            item.CustomerName,
            item.CustomerNumber,
            Environment.NewLine);
    }

    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(sb.ToString());
    writer.Flush();
    stream.Position = 0;

    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("text/csv");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
    return result;
}

EDIT: added this line:

result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };

still doesn't work

I call it like this:

<a id="export" href="/Relay/Billing/Export" class="btn btn-primary">Export</a>

and also tried it like this:

$("#export").click(function () {
    $.post("/Relay/Billing/Export", { type: $("#discountType").val() })
      .done(function (data) {
      });
});

Still no Save As box

like image 487
ShaneKm Avatar asked Apr 29 '15 15:04

ShaneKm


People also ask

How do I download data from Web API?

In this article, I will use a demo Web API application in ASP.NET Core to show you how to transmit files through an API endpoint. In the final HTML page, end users can left-click a hyperlink to download the file or right-click the link to choose “ Save Link As ” in the context menu and save the file.

CAN REST API use CSV?

You can use REST APIs to export data from your Maximo® system into an external system or application and to import data from an external system or application into your Maximo system. You can export and import JSON, XML. or CSV files.


1 Answers

I do not know whether this is proper protocol but this is how I did it before. So you have a web page from which you will invoke an API that will response with the file and it should be handled by browser's save as dialog.

The HTML:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <script type="text/javascript">
        function save() {
            window.open('http://localhost:45719/api/home?id=12', '_blank', '');
        }
    </script>
</head>
<body>
    <a class="btn btn-primary" onclick="save()">Export</a>
</body>
</html>

The action:

public HttpResponseMessage Get(int id)
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write("Hello, World!");
    writer.Flush();
    stream.Position = 0;

    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
    return result;
}

This is working for me in both Chrome and Firefox latest.

like image 154
lbrahim Avatar answered Sep 20 '22 07:09

lbrahim