0

I'm trying to export data from my database to CSV using return File(bytes, contentType, fileName);

This code done based on accepted answer here

I'm expecting a download to start in my browser, but what happens instead, is that the intended contents of the file gets written out to the response body and the response headers have a weird value for content-disposition.

Having updated my response by manually adding a content disposition and sending the return value, I see the content disposition now correctly reads content-disposition: attachment; filename=foo.csv

I'm still not getting my download so I replaced the ; with a , but that didn't help either.

Here's the headers:

content-disposition: attachment, filename=foo.csv
content-encoding: gzip
content-type: text/csv
date: Wed, 21 Apr 2021 06:54:40 GMT
server: Microsoft-IIS/10.0
vary: Accept-Encoding
x-powered-by: ASP.NET

The response does contain the data though...

enter image description here

So the question is how on earth do I get this data output to an actual file that'll be automatically downloaded on the browser?

I'd like to avoid saving files to the server first if at all possible because it's a bit of a nightmare in regard to maintaining.

Ortund
  • 8,095
  • 18
  • 71
  • 139
  • I never saw header fields in lower case and the file name in Content-Disposition without quotation marks – Klamsi Apr 21 '21 at 07:06
  • Behavior doesn't change with the header formatted as such: `content-disposition: attachment; filename="foo.csv"` – Ortund Apr 21 '21 at 07:13
  • The response body will always contain the data, in cases where the browser decides to download it as well. The `content-disposition: attachment...` is meant to encourage the browser to download, though it doesn't have to. For example if you return a PDF most browsers open it in their PDF viewer instead of prompting a download. – juunas Apr 21 '21 at 07:31
  • What behaviour are you seeing in the browser exactly? Does it just show the contents in the browser window? Have you tried "application/csv" instead of "text/csv"? – juunas Apr 21 '21 at 07:32
  • I found the issue and posted an answer. Thanks for the assistance. – Ortund Apr 21 '21 at 10:00

1 Answers1

0

I feel like a bit of a noob right now because I discovered the cause of the problem was nothing at all to do with the way the server was handling the request or building the response.

The problem is the way I was handling it on the front end.

    $.get("/r/foo/export" + args, null, function (data) {
        console.log(data);
    });

My understanding was that this would trigger the download since I'm requesting it on this url but this isn't sufficient or correct.

Having changed this ajax get request to a redirect triggers the download on the browser perfectly.

    location.href = "/r/foo/export" + args;
Ortund
  • 8,095
  • 18
  • 71
  • 139