Web API return csv file

前端 未结 1 873
北荒
北荒 2020-12-03 11:15

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 jquer

相关标签:
1条回答
  • 2020-12-03 11:54

    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.

    0 讨论(0)
提交回复
热议问题