Search code examples
javascriptfiledownloadmime

Create a downloadable attachment from JavaScript?


I'm getting varbinary data(file contents) from the DB along with the file name and mime type. Depending on how many files are there, I need to display links for those files on the web page. When the user clicks on a link, that file should get downloaded. Since the links will get created dynamically, I think i will have to call a client side function to handle the downloading. But I don't know how this can be done. On the server side(C#) we can use FileContentType, but how can this be achieved through JavaScript? Also, since I do not have a physical file and just it's contents, I will have to somehow create this file.


Solution

  • You should just create links to C# server-side actions that dynamically serve the contents.

    Create an action in your controller that takes an ID of some sort and returns the file. You can then use <a> tags that point directly to this action's URLs (with different IDs). You don't need any Javascript.