Simple example for UPLOADING FILES IN ASP.NET
In this post we will see a small example to understand the file upload control in Asp.net. For this take a fileupload control, button controls and a label on form default.aspx, code given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </style> </head> <body> <form id="form1" runat="server"> <p> <asp:FileUpload ID="FileUpload1" runat="server" /> </p> <p> <asp:Label ID="lblContentType" runat="server"></asp:Label> </p> <p> <asp:Button ID="btnUpload" runat="server" onclick="btnUpload_Click" Text="Upload" /> </p> </form> </body> </html> |
And then add a new folder “uploads” to your website. The C# code in the code behind file is like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnUpload_Click(object sender, EventArgs e) { string path = Server.MapPath("." + "//uploads//" + FileUpload1.FileName); if (FileUpload1.HasFile) { lblContentType.Text = FileUpload1.PostedFile.ContentType; if (System.IO.File.Exists(path)) { Response.Write("file already exists.."); } else { FileUpload1.SaveAs(path); Response.Write("Upload successfull.."); } } } } |
In the above code you can see Server.MapPath, here we are saving the uploaded file in uploads folder in our asp.net website.
You can see the image below to understand output,Here it is a screen shot when a ms word 2007 file is uploaded.