How to upload file in asp.net?

ASP.NET – File Uploading.

Basic syntax


<asp:FileUpload ID= "Uploader" runat = "server" />

Write the below code in HTML Document Default.aspx.


<body>
<form id="form1" runat="server">
<div>
<h3> Uploading File :</h3>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<br /><br />
<asp:Button ID="btnadd" runat="server"
onclick="btnadd_Click" Text="Add"
Width="85px" />
<br /><br />
<asp:Label ID="lblmessage" runat="server" />
</div>
</form>
</body>

Open Default.aspx.cs file and add following namespace:

System.IO;

After added namespace write the following code into Default.aspx.cs:


protected void btnadd_Click(object sender, EventArgs e)
{
StringBuilder strbl = new StringBuilder();
if (FileUpload1.HasFile)
{
try
{
strbl.AppendFormat(" Uploading file: {0}",
FileUpload1.FileName);
//saving the file
FileUpload1.SaveAs("<c:\\SaveDirectory>" +
FileUpload1.FileName);
//Showing the file information
sb.AppendFormat("<br/> Save As: {0}",
FileUpload1.PostedFile.FileName);
strbl.AppendFormat("<br/> File type: {0}",
FileUpload1.PostedFile.ContentType);
strbl.AppendFormat("<br/> File length: {0}",
FileUpload1.PostedFile.ContentLength);
strbl.AppendFormat("<br/> File name: {0}",
FileUpload1.PostedFile.FileName);
}
catch (Exception ex)
{
strbl.Append("<br/> Error <br/>");
strbl.AppendFormat("Unable to save file <br/> {0}",
ex.Message);
}
}
else
{
lblmessage.Text = strbl.ToString();
}
}

Hope it help you better:

About the Author

avatar