Surendra Sharma

Surendra Sharma

Search This Blog

Wednesday, July 10, 2013

How to download file async in ASP.NET

While developing ASP.NET site, its common feature to allow download of a file.
Along with download large file, site should allow user to do other tasks on the page i.e. allow user to download file async.

Here are the guidelines for doing it

  • Create two web page - default.aspx and Download.aspx
  • On default.aspx take one hidden frame and button to download as below

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
 <script type="text/javascript" language="javascript">

     function DownLoadFile(uid) {
         var iframe = document.getElementById("ifrmDownloadframe");
            iframe.src = uid;
            return false;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <iframe style="display: none" id="ifrmDownloadframe"></iframe>
    <div>
    Current Date Time is <asp:Label ID="Label1" runat="server" ></asp:Label>
    <br />
        <asp:Button ID="btnDateTime" runat="server" Text="Show Date Time"
            onclick="btnDateTime_Click" />
        <asp:Button ID="btnDownload" runat="server" Text="Download" />
    </div>
    </form>
</body>
</html>

  • Set Download.aspx page with required query string as a frame source as below from default.aspx

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Label1.Text = DateTime.Now.ToString();
            btnDownload.Attributes.Add("onclick", DownloadShippedFile(100));
        }
    }

    protected void btnDateTime_Click(object sender, EventArgs e)
    {
        Label1.Text = DateTime.Now.ToString();
    }

    private string DownloadShippedFile(int Id)
    {
        string result = string.Empty;

        try
        {

            string key = string.Format("Type=DownloadEmpFile&EmployeeId={0}", Id);
            string strURL = Request.ApplicationPath + "/Download.aspx?" + key;
            result = "return DownLoadFile('" + strURL + "');";
        }
        catch (Exception ex)
        {
            result = string.Format("alert('{0}');return false;", ex.Message);
        }

        return result;
    }
}


  • On Download.aspx, get filepath from query string and force file to download on browser

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString.Count > 0 && Request.QueryString["EmployeeId"] != null)
        {
            //Based upon id get file name from database or from some where else. I am considering direct file name
            string filePathFromDatabase = @"\\xyz\abc.zip";
            DownloadFile(filePathFromDatabase);
        }
    }


    private void DownloadFile(string sFileName)
    {
        FileStream fileStream = new FileStream(sFileName, FileMode.Open, FileAccess.Read);

        byte[] buffer = new byte[(int)fileStream.Length];
        fileStream.Read(buffer, 0, (int)fileStream.Length);
        fileStream.Close();

        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        if (sFileName.EndsWith(".html"))
            Response.ContentType = "text/html";
        else
            Response.ContentType = "application/octet-stream";

        Response.AddHeader("Content-Length", buffer.Length.ToString());
        Response.AddHeader("Content-Disposition", "attachment;filename=\"" + sFileName + "\"");
        Response.BinaryWrite(buffer);
        Response.Flush();
        Response.End();
    }



Please leave your comments if it is useful for you.

No comments:

Post a Comment