Introduction : FileUpload Control is used to Upload files in the server. For eg., when User wants to upload their picture to show on a profile then this control should be used to upload any kind of file in the server, be it .doc, .pdf, .gif, .Jpeg etc.,FileUpload Control is used to Upload files in the server. For eg., when User wants to upload their picture to show on a profile then this control should be used to upload any kind of file in the server, be it .doc, .pdf, .gif, .Jpeg etc., ASP.NET FileUpload Control itself is a class which is present under System.Web.UI namespace.
Important Properties of Asp.NET Webserver FileUpload control are given below. You can Set /Get these properties at Design time or at Runtime.
Enabled - Boolean Value - FileUpload control is used to enable the user to select Files or not.
Visible - Boolean Value - set true if you want user to see FileUplaod control in your webpage.
Apart from the above property there are some other properties to set FileUpload control style.
Events available in Asp.Net Web server FileUpload Control are:
Init Load PreRender UnLoad
Let's see an example
Your .aspx code will look like this for a WebServer Control FileUpload <asp:FileUpload ID="FileUpload1" runat="server" />
Full Html Code Used in this sample project:
NOTE:You have to add enctype="multipart/form-data" on FormTag <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>FileUpload control example - www.dotnetspark.com</title> </head> <body > <form id="form1" runat="server" enctype="multipart/form-data"> <div> <asp:Label ID="lblPageMessage" runat="server" Text="FileUpload Control Example"></asp:Label> </div> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="btnUpload" runat="server" onclick="btnUpload_Click" Text="Upload" /> <br /> <br /> <asp:Label ID="lblSuccessMessage" runat="server" Font-Bold="True" ForeColor="#0033CC" Visible="False">File Uploaded Successfully</asp:Label> </form> </body> </html>
And to assign value to the textbox programmatically btnUpload_Click form the .cs file protected void btnUpload_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { try { string filePathToSave = Server.MapPath("./") + System.IO.Path.GetFileName(FileUpload1.FileName); FileUpload1.PostedFile.SaveAs(filePathToSave); lblSuccessMessage.Text = "File uploaded successfully to " + filePathToSave; lblSuccessMessage.Visible = true; } catch (Exception ex) { throw ex; } } }
|