C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ASP.NET Web Forms FileUploadIt is an input controller which is used to upload file to the server. It creates a browse button on the form that pop up a window to select the file from the local machine. To implementFileUpload we can drag it from the toolbox in visual studio. This is a server side control and ASP.NET provides own tag to create it. The example is given below. < asp:FileUpload ID="FileUpload1" runat="server"/> Server renders it as the HTML control and produces the following code to the browser. <input name="FileUpload1" id="FileUpload1" type="file"> This control has its own properties that are tabled below.
FileUpload Property WindowExampleHere, we are implementing file upload control in web form. // WebControls.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs" Inherits="WebFormsControlls.WebControls" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <p>Browse to Upload File</p> <asp:FileUpload ID="FileUpload1" runat="server" /> </div> <p> <asp:Button ID="Button1" runat="server" Text="Upload File" OnClick="Button1_Click" /> </p> </form> <p> <asp:Label runat="server" ID="FileUploadStatus"></asp:Label> </p> </body> </html> Code// WebControls.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebFormsControlls { public partial class WebControls : System.Web.UI.Page { protected System.Web.UI.HtmlControls.HtmlInputFile File1; protected System.Web.UI.HtmlControls.HtmlInputButton Submit1; protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { if ((FileUpload1.PostedFile != null) && (FileUpload1.PostedFile.ContentLength > 0)) { string fn = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName); string SaveLocation = Server.MapPath("upload") + "\\" + fn; try { FileUpload1.PostedFile.SaveAs(SaveLocation); FileUploadStatus.Text = "The file has been uploaded."; } catch (Exception ex) { FileUploadStatus.Text = "Error: " + ex.Message; } } else { FileUploadStatus.Text = "Please select a file to upload."; } } } } Create a directory into the project to store uploaded files as we did in below screen shoot. Output: Output: Run the code, it produces following output. We are uploading a file c# programs.txt. It displays a successful file uploaded message after uploading as shown in the following screenshot. The file is stored into upload folder. Look inside the folder, it shows the uploaded file is present.
Next TopicASP.NET Upload Multiple Files
|