简体   繁体   中英

WebApi download response as file

I have an issue with my WebApi. Based on the request, the response is returned either as json or csv . For serialization I use NewtonSoft.Json and my own CsvMediaTypeFormatter . As long as I test it from Postman, the response works as expected.

What I struggle with it that I'd like to force the browser to save the file in case the response is csv . To achieve that, in my CsvMediaTypeFormatter I overrode the SetDefaultContentHeaders method as follows:

public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
{
    base.SetDefaultContentHeaders(type, headers, mediaType);

    headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                                 {
                                     FileName = "content.csv"
                                 };
}

When I test my API using Postman, I see the csv content as the body, also the headers show content-disposition: attachment; filename=content.csv content-disposition: attachment; filename=content.csv .

But when it's hit from the browser (I tried Firefox, Chrome and Edge), there's no "Save file as..." dialog. However, the dev tools show the call being made and the response having the content-disposition header value.

I tried with various Content-type values: text/csv , text/plain , application/octet-stream or application/x-unknown , but no success.

Any ideas what I'm doing wrong?

In case you use some js framework for making the http call, you might need to manually dump the content to a file. Below are examples for AngularJS and Angular2.

AngularJS:

this.$http(req).success(data => {
    const file = new Blob([data],
        {
            type: "text/csv"
        });

    const a = document.createElement("a");
    a.href = URL.createObjectURL(file);
    a.target = "_blank";
    a.download = `yourfilename.csv`;
    document.body.appendChild(a);
    a.click();
});

Angular2+

downloadFile(data: Response){
    const file = new Blob([data],
        {
            type: "text/csv"
        });
    var url= window.URL.createObjectURL(blob);
    window.open(url);
}

How to create and save file to local fileSystem using AngularJS?

How do I download a file with Angular2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM