Monday, May 18, 2015

Clicking a button to download a server file sent as a FileContentResult via ASP.NET Web Api

Scenario:
I have a Web Api controller that returns a .csv file as a FileContentResult.
In the UI, I have a <button> element that when clicked, I want it to trigger the file download to the local computer.

Solution:
After playing a bit with ajax calls and trying to use an anchor element instead a button to follow what many web posts suggest - which is to add "data" and "chartset" attributes plus the server uri that returns the content, like

'data:text/csv;charset=UTF-8,' + encodeURI(...)
and having no success, I then switched to a different approach - also vastly suggested on the web - to simply have the browser's window.location.href attribute set to the server uri that returns the file, like


window.location.href= encodeURI(...);
The simplest and neatest solution for this problem.

No comments:

Post a Comment