Skip to main content

How to download file asynchronously from webserver in asp.net

In this post I am going to show how to download file asynchronously from server using asp.net.
  •  Open Visual Studio and create a new WebApplication or WebSite
  •  Open Default.aspx page and paste following code


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
    Async="true" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
</head>
<body>
    <script type="text/javascript">
        function WaitProgress() {
            $("#Indicator").text("please wait...");
        }
        function FinishProgress(contentState) {
            $("#Indicator").text(contentState);
        }
    </script>
    <form id="form1" runat="server">
    <asp:Button ID="btnDownload" runat="server" Text="DownLoadData" OnClientClick="WaitProgress();"
        OnClick="btnDownload_Click" />
    <p id="Indicator">
    </p>
    </form>
</body>
</html>

  • Open Default.aspx.cs file and pate following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Net;

public partial class _Default : System.Web.UI.Page
{
    private const string FILE_PATH = @"C:\Temp\test.pdf";
    protected void btnDownload_Click(object sender, EventArgs e)
    {
        DownLoadFile();
    }
    private void DownLoadFile()
    {
        //define the url
        string url = "http://www.daikodo.com/genki-back/back-img/10genki-2.jpg";
        //define the local path
        string filepath = FILE_PATH;
        Uri uri = new Uri(url);
        WebClient client = new WebClient();
        client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
        client.Credentials = new NetworkCredential();
        client.DownloadFileAsync(uri, filepath);
    }

    void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {
        string contentState = "File Downloaded Successfully!!!";
        if (e.Error != null)
        {
            contentState = e.Error.Message;
        }
        else
        {
            object userstate = e.UserState;
            this.ClientScript.RegisterStartupScript(this.GetType(), "finishDownload", "FinishProgress('" + contentState + "');", true);
        }
    }



}

Comments

Popular posts from this blog