Pages

Friday, August 16, 2013

How to Download and Upload File in Asp.net

In this article we are explaining how to download and Upload file in Asp.net. To download and upload file we have to use an namespace 'System.Net' and 'System.IO' to access file store on local drive at the time of uploading. To upload file visual studio provide 'FileUpload' control by which we can easily upload file.
Code for Download.
  protected void DownloadBtn_Click(object sender, EventArgs e)
    {
        try
        {
            string filePath = "54825/MP9004001913.jpg";
            WebClient wbCli = new WebClient();
            HttpResponse HttpResp = HttpContext.Current.Response;
            HttpResp.Clear();
            HttpResp.ClearContent();
            HttpResp.ClearHeaders();
            HttpResp.Buffer = true;
            HttpResp.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath(filePath) + "\"");
            byte[] data = wbCli.DownloadData(Server.MapPath(filePath));
            HttpResp.BinaryWrite(data);
            HttpResp.End();
        }
        catch (Exception ex)
        {
        }

    }
Code for Upload.
In 'Default.aspx' add following control.

<form id="form1" runat="server">
    <div>
   
    </div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="UploadBtn" runat="server"  Text="Save" OnClick="Button2_Click" />
        <asp:Label ID="lblMsg" runat="server" Text="Label"></asp:Label>
    </form>
In 'Default.aspx.cs' write following code.
protected void UploadBtn_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            try
            {
                string filename = Path.GetFileName(FileUpload1.FileName);
                FileUpload1.SaveAs(Server.MapPath("~/") + filename);
                lblMsg.Text = "Upload status: File uploaded!";
            }
            catch (Exception ex)
            {
                lblMsg.Text = "error in file uploading: " + ex.Message;
            }
        }

    }

No comments:

Post a Comment