FileUpload example: how to use FileUpload control in asp.net
Now we see how to upload a file in asp.net. For this example you need to create a web form as like FileUploadControl.aspx. Put a label, a Button and a FileUpload control in this web form. Then create a folder C:\UploadFolder. When someone selects a file and presses the button, his selected file uploads in UploadFolder. And the Label control show that file’s name, size and type. If any error occurred, the Label also shows it.
FileUploadControl.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e) {
if (FileUpload1.HasFile)
try {
FileUpload1.SaveAs("C:\\UploadFolder\\"+FileUpload1.FileName);
Label1.Text = "Uploaded File Name: " +
FileUpload1.PostedFile.FileName +
"<br />File Size: " +
FileUpload1.PostedFile.ContentLength +
"<br />File Type: " +
FileUpload1.PostedFile.ContentType;
}
catch (Exception ex){
Label1.Text = "Error occured: " + ex.Message.ToString();
}
else{
Label1.Text = "Select a file for upload";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>FileUpload example: how to use FileUpload control in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="CornflowerBlue"></asp:Label>
<br /><br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Upload this File" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>