ASP.NET File Upload

The FileUpload server control provided by ASP.NET is a powerful control that was quite difficult to achieve in the days of Active Server Pages 3.0. The FileUpload server control allows your end-users to upload one or more files to your server. You can upload maximum filesize of 4MB . If you want to upload larger files, you can control the size of the files that are uploaded by working with settings in either the web.config.comments or web.config file.

file-upload

Simply drag and drop the File upload control on you form and write the code in the upload button click event. You can specify where you want to save the uploaded file in your server.

VB.Net
FileUpload1.SaveAs("C:\files\" + FileUpload1.FileName)
C#
FileUpload1.SaveAs("C:\\files\\" + FileUpload1.FileName);

Default.aspx

<!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 id="Head1" runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:FileUpload ID="FileUpload1" runat="server" /> <br /> <br /> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" Width="123px" /> <br /> <br /> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </div> </form> </body> </html>
Full Source | C#
using System; public partial class _Default : System.Web.UI.Page { protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) try { FileUpload1.SaveAs("C:\\files\\" + FileUpload1.FileName); Label1.Text = "File Uploaded Successfully !! " + FileUpload1.PostedFile.ContentLength + " kb"; } catch (Exception ex) { Label1.Text = "File Upload Failed !! " + ex.Message.ToString(); } else { Label1.Text = "Please select a file "; } } }
Full Source | VB.NET
Partial Class _Default Inherits System.Web.UI.Page Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click If FileUpload1.HasFile Then Try FileUpload1.SaveAs("C:\files\" + FileUpload1.FileName) Label1.Text = "File Uploaded Successfully !! " + FileUpload1.PostedFile.ContentLength.ToString + " kb" Catch ex As Exception Label1.Text = "File Upload Failed !! " + ex.Message.ToString() End Try Else Label1.Text = "Please select a file " End If End Sub End Class



Click the following links to see full source code

C# Source Code
VB.NET Source Code
default.aspx.cs
default.aspx.vb