Downloading a File Using Web Api with Jquery or Knockout

This short walk-through is intended for those who work with WebApi and want to perform file download using Knockout or JQuery.

While working on a project that uses Knockout.js for front end scripting and Asp.Net Web API as back-end service layer, we had to implement file downloading functionality using Ajax.

Lets Code

This method in Api returns a FileStream, sets ContentDisposition and ContentType to tell browser the type of content is a file and browser popups save file dialog. GetFileStream method is defined in a Helper class that just converts a file into filestream

Knockout Devs

Knockout developers have to create a view and a viewModel. The viewModel will expose a caller for API while the view will simply have an anchor tag which will have its click event bound to viewModel’s funtion.

ViewModel will have the following caller function

While the view’s anchor tag will look like

JQuery Devs

Jquery developers can define an anchor tag <a> in Html, build href  and set to the tage using Jquery.

With the hope it helps 🙂 Cheers..

Leave a Reply

Your email address will not be published. Required fields are marked *