Asp.net File upload Example

File upload example in asp.net c# application, hHere we learn how to upload file on web server in Asp.net application.

How to upload file in Asp.net Application

asp.net file upload example

What we need for File Uploading in Asp.net website

ASP.NET provides two type of control to upload files on web server.

  • FileUpload - this is ASP.NET web control
  • HtmlInputFile - this is HTML server control

Both asp.net controls allow you to upload files, images, the difference is that FileUpload control sets the encoding of the form.
So, we look at both example with code syntax

Asp.net file upload control

Let's write the html code, place one asp:FileUpload and a asp:Button control in your form

<form id="form1" runat="server">
<div>
<%=ViewState["result"] %>
</div>
<div style="padding: 15px;">
<asp:FileUpload ID="fuUser" runat="server" />
<asp:Button ID="btnUpload" Text="Upload File" runat="server" OnClick="btnUpload_Click" />
</div>
</form>
Asp net file upload button click

Now open your codebehind file, inside button click event write the following code, you need to set file upload default directory in asp.net code behind file

protected void btnUpload_Click(object sender, EventArgs e)
{
    string userFolderPath = Server.MapPath("~/userdocs");            
    if (fuUser.HasFile)
    {
        fuUser.SaveAs(userFolderPath + "/" + fuUser.FileName);
        ViewState["result"] = "File has been uploaded successfully";
    }
    else
    {
        ViewState["result"] = "Please select a file";
    }
}
    
Asp.net file upload validation

Now above code will allow user to upload any type of file on your web server, which can be dangerous, so now we learn how to restrict all other file types other than the type we allow

Write the following RegularExpressionValidator control to check the file type before uploading

<asp:RegularExpressionValidator 
id="regexpFileUpLoadValidator" runat="server" 
ErrorMessage="Upload jpg, gif or png only." ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*)) (.jpg|.JPG|.gif|.GIF|.png|PNG)$" ControlToValidate="fuUser">
</asp:RegularExpressionValidator>

Now user can upload only jpg/png/gif file type

HtmlInputFile Example

Another way of uploading file is HttpPostedFile, actually this is how we used to upload file in classic asp days, let’s look at the same implementation Asp.net code.

Write the following code in your html

<input type="file" runat="server" id="fuControl" />
<asp:Button ID="btnFileUpload" Text="Upload File" runat="server" OnClick="btnFileUpload_Click"  />

Now here is the serverside code in button click event

protected void btnFileUpload_Click(object sender, EventArgs e)
{
    string userFolderPath = Server.MapPath("~/userdocs");
    HttpPostedFile _file = fuControl.PostedFile;

    if (_file != null)
    {
        _file.SaveAs(userFolderPath + "/" + _file.FileName);
        ViewState["result"] = "File has been uploaded successfully";
    }
}

check if same file exists

Sometimes you may want to check if the same file is already exists on server, then instead of uploading again you would display a message on user that "Same file already Exists".

string userFolderPath = Server.MapPath("~/userdocs");
if (fuUser.HasFile)
{
    string fullPath = userFolderPath + "/" + fuUser.FileName;
    if (File.Exists(fullPath))
    {
        ViewState["result"] = "Same file already Exists";
    }
    else
    {
        fuUser.SaveAs(fullPath);
        ViewState["result"] = "File has been uploaded successfully";
    }
}
asp.net file upload extension validation

The above code will allow user to upload all type of files. In earlier example we implemented a regular expression control to restrict other file type. But here we check the file type in server side code to make sure only images are allowed

HttpPostedFile _file = fuControl.PostedFile;
// check the following property
if (_file.ContentType == "image/jpg" 
        || _file.ContentType == "image/jpeg"
        || _file.ContentType == "image/gif"
        || _file.ContentType == "image/png")
    {
        fuUser.SaveAs(fullPath);
        ViewState["result"] = "File has been uploaded successfully";
    }

You can allow file type as per your business requirement

Asp.net file upload code C#

Here is the complete server side code for uploading file in Asp.net C# web application

protected void btnUpload_Click(object sender, EventArgs e)
{
string userFolderPath = Server.MapPath("~/userdocs");
HttpPostedFile _file = fuUser.PostedFile;
if (fuUser.HasFile)
{
string fullPath = userFolderPath + "/" + _file.FileName;
if (File.Exists(fullPath))
{
ViewState["result"] = "Same file already Exists";
}
else if (_file.ContentType == "image/jpg" || _file.ContentType == "image/jpeg"
|| _file.ContentType == "image/gif"
|| _file.ContentType == "image/png")
{
fuUser.SaveAs(fullPath);
     ViewState["result"] = "File has been uploaded successfully";
        }
        else
        {
                   
            ViewState["result"] = "Upload only image file jpg, gif, png";
        }
    }
    else
    {
        ViewState["result"] = "Please select a file";
    }
}

You may be interested to look at following examples!

 
Hire Asp.Net Developer
Asp.net FileUpload Control
Asp.net Interview Questions Answers
Asp.net MVC interview
Asp.net Core question
Asp.net application development tutorials with real-time examples create asp.net web application with SQL database step-by-step.
Asp.net FileUpload Example
Asp.Net C# Examples | Join Asp.Net Course | Learn Asp.net MVC | Asp.net Core Tutorial