Click here to Skip to main content
13,452,880 members (54,350 online)
Click here to Skip to main content
Add your own
alternative version


47 bookmarked
Posted 29 Jan 2010

File Download Using JavaScript

, 29 Jan 2010
Rate this:
Please Sign up or sign in to vote.
An article on how to download a file using JavaScript


I know there are many developers looking for this kind of solution like I was looking. I had the same requirement to download the file from the server using JavaScript and with out postbacking the full page. The beauty of this is, it will work in IE/Firefox/Chrome browsers. I have not used ScriptManager/UpdatePanel anything rather I used Handler and normal JavaScript code. Handler is used to write the response back to the page. I have noted down the steps you may use in your programming. I can not use ActiveXObject in Firefox to create excel object in JavaScript because ActiveXObject will not work in Firefox.

How Did I Do This?

  1. Add span tag on the page which will work as a link
  2. Create FileHandler.ashx to write the response back to the page.
    public void ProcessRequest(HttpContext context)
            fileName = HttpUtility.UrlDecode(context.Request.Params["fileName"]);
            string FullFilePath = context.Server.MapPath("~/Common/Files/" + fileName);
            FileInfo file = new FileInfo(FullFilePath);
            if (file.Exists)
                context.Response.ContentType = 
    	    ("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
                context.Response.AddHeader("Content-Length", file.Length.ToString());

    You can use any MIME Type according to your requirement. I have showed some of the MIME types you can use in your application. For more MIME types, list

    public enum MIMEType
    public class MIMETypeUtility
        public static string MIMETypeDescription(Enum mimeType)
            FieldInfo fi = mimeType.GetType().GetField(mimeType.ToString());
            DescriptionAttribute[] attributes = 
                	(typeof(DescriptionAttribute), false);
            if (attributes.Length > 0)
                return attributes[0].Description;
                return mimeType.ToString();
  3. Create FileHandler.js file to do the main work. It will create an iframe dynamically and which has width, height and border as 0. Then create form tag with one input control to pass filename (e.g. ExcelFile.xls) when you submit an iframe.
    var createFrame = function() 
        var frame = document.createElement("iframe"); = "fileFrame"; = "fileFrame";
        generateIFrameContent(); = "0px"; = "0px"; = "0px";
  4. GetExcelFile function will pass Excel file name as parameter and will submit an iframe window and handler will run the code and writes the file response back to the page and the user will get open/save/cancel dialog window.
    var getExcelFile = function()
        var frmWindow = getIFrameWindow();
        var fileName = frmWindow.document.getElementById("fileName");
        fileName.value = encodeURI("ExcelFile.xls");
        var frm = frmWindow.document.getElementById("frmFile");
  5. Create LoadScript.aspx page to add scripts to the page response. Here you can add any number of scripts and I prefer this way where I can hide the JavaScript and the location of the script file in page source at runtime.
    private void loadScript()
            List<string> scripts = new List<string>();
                bool isStyles = this.GetType().BaseType.Name == "Styles";
                this.Response.ContentType = isStyles ? "text/css" : "text/javascript";
                byte[] data = null;
                    StringBuilder sb = new StringBuilder();
                    foreach (string str in scripts)
                    data = new ASCIIEncoding().GetBytes(sb.ToString());
                catch (Exception ex)
                    throw ex;
                this.Response.AddHeader("Content-Length", data.LongLength.ToString());
            catch (Exception ex)
                throw ex;
  6. Add the following code to the FileHandler.aspx page to load scripts and startupscript with initialization of JavaScript function.
    protected void Page_Load(object sender, EventArgs e)
        Type type = this.GetType();
        if (!this.ClientScript.IsClientScriptIncludeRegistered(type, "scrScripts"))
    		(type, "scrScripts", "Common/Loaders/LoadScripts.aspx");
        if (!this.ClientScript.IsStartupScriptRegistered(type, "scrHandlerStartUp"))
    		(type, "scrHandlerStartUp", GetStartUpScript(), true);
    private string GetStartUpScript()
        return "try{{var handler = new FileHandler();handler.init();}}catch(e)
    	{{document.getElementById('divNotLoaded').style.display = '';}}";


You can use AJAX (Scriptmanager + Updatepanel) to download the file from server, but you have to post back the page. This technique is light weight on the page. I had the requirement in my project to get the data from database and create an Excel file and insert the data and download the file to user machine. And my total website is using AJAX (JS+WebServices and no updatepanel), in this case I cannot use any server controls because that will post back my full page and I do not want that to happen. So after much R&D and many ways, this is one technique I have come up to use and it's working successfully in the production. I am available at for any questions you might have.


  • 29th January, 2010: Initial version


This article, along with any associated source code and files, is licensed under The Common Public License Version 1.0 (CPL)


About the Author

Phani Nadigadda
Software Developer
United States United States
I started development with Visual Basic 6.0 and then upgraded to Visual Studio .Net and working on .net for 7+ years now.

You may also be interested in...


Comments and Discussions

Generali creates error in IE6 Pin
jk.shan16-Jan-11 20:41
memberjk.shan16-Jan-11 20:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.180318.3 | Last Updated 29 Jan 2010
Article Copyright 2010 by Phani Nadigadda
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid