Content-Disposition:attachment not triggering download dialog

Yaron Schwimmer picture Yaron Schwimmer · Nov 4, 2014 · Viewed 21.4k times · Source

I've encountered some unexpected behavior when trying to create a file download functionality on my NodeJS server. I have a REST (express) API that calls for some export data function, which creates a CSV file on the server and uses res.download('path/to/file') to trigger the download. Response headers include

Content-Disposition:attachment; filename="indicators.csv"
Content-Length:30125
Content-Type:text/csv; charset=UTF-8

so everything seems to be in order.

The thing is, I get the response from the server as plain text. The response has all the data the CSV file contains, but does not trigger the browser's file download dialog like I intended. I tried both on Chrome and FF. The problem persists in both.

Any ideas?

Update

I managed to make it work by creating a dummy form, and using its submit action to make my AJAX call. But it's an ugly hack, and I'm still looking for a more elegant solution.

Answer

Roman Pletnev picture Roman Pletnev · Aug 31, 2015

Headers are not the issue. The issue is that you are querying the download url via an ajax call, which will not invoke the browser download dialog. Your options boil down to the following:

  1. Use a form that is submitted to your download url. Instead of having a visible form a user has to interact with, create a form with JavaScript and submit it programmatically by calling form.submit - Handle file download from ajax post

  2. Point window.location to the download url. You can do this in the current window - download file using an ajax request , or in a new one - res.download() not working in my case