In this article, we are going to learn how to upload file by using FileUpload control in asp.net.
In designer file:
In designer file, create a FileUpload control and a Button control and a Label control to display appropriate error message.
Designer file look like as below.
Below is the designer code.
table style="border: 1px solid black;">
tr>
td colspan="2">
asp:Label ID="lblMessage" runat="server" ForeColor="Red">asp:Label>
td>
tr>
tr>
td>
asp:FileUpload ID="FileUpload1" runat="server" />
td>
td>
asp:Button ID="btnUpload" runat="server" Text="Upload File" OnClick="btnUpload_Click"/>
td>
tr>
table>
In Code-Behind file:
Step 1: Create a folder with name "UploadFolder" in root directory of application.
Step 2: Below is the code to upload a file without checking file size and file types (extension). We will simply upload a file.
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileUpload1.SaveAs(Server.MapPath("~/UploadFolder/" + FileUpload1.FileName));
lblMessage.Text = "File uploaded successfully";
}
else
{
lblMessage.Text = "Please select a file";
}
}
Step 3: Below is the code to upload a file with file size should not be greater than 1MB.
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
// 1MB =1048576 bytes
if (FileUpload1.PostedFile.ContentLength > 1048576)
{
lblMessage.Text = "Your file size is greater than 1MB";
}
else
{
FileUpload1.SaveAs(Server.MapPath("~/UploadFolder/" + FileUpload1.FileName));
lblMessage.Text = "File uploaded successfully";
}
}
else
{
lblMessage.Text = "Please select a file";
}
}
Step 4: Below is the code to upload a file with file size should not be greater than 1MB and file extension should be .pdf or .docx or .rar.
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
// 1MB =1048576 bytes
if (FileUpload1.PostedFile.ContentLength > 1048576)
{
lblMessage.Text = "Your file size is greater than 1MB.";
}
else
{
String extension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (extension.ToLower() == ".pdf" || extension.ToLower() == ".docx" || extension.ToLower() == ".rar")
{
FileUpload1.SaveAs(Server.MapPath("~/UploadFolder/" + FileUpload1.FileName));
lblMessage.Text = "File uploaded successfully";
}
else
{
lblMessage.Text = "Only file with extension .pdf or .docx or .rar are allowed.";
}
}
}
else
{
lblMessage.Text = "Please select a file";
}
}