What is the best way to download file from server

First you can create the file from a handler .ashx

Let say that you have the file for downloading at download.ashx and you have some parametres to pass from your javascript, eg download.ashx?p1=8827&p2=8831 to know what you going to create.

Then on your javascript you simple can make a redirect as

window.location = "download.ashx?p1=8827&p2=8831";

or alternative you can use the window.open for do the same think

window.open("download.ashx?p1=8827&p2=8831");

and your file will start the download.

Just make sure that you have set the header of attachment, and the correct contenttype on your handle eg:

  HttpContext.Current.Response.ContentType = "application/octet-stream";
  HttpContext.Current.Response.AddHeader("Content-Disposition", 
                    "attachment; filename=" + SaveAsThisFileName);

Simple and clear, both tested and working.

Also you may interesting on this answer: How to handle errors.

Leave a Comment