How to upload a file in asp.net using fileupload control c#

Here is an example which is for how to upload and save a file through fileupload control in asp.net c# with validating files content type, size of file and extension of file as you want .jpg or .png etc.

The code given below, save a posted file with following validation check

  • Posted data must contain a file (posted file must be exist)
  • Extension must be .jpg, .png or .gif
  • Mime Type (Content Type) must be image/jpeg, image/png or image/gif
  • Size of file must be less than 1MB


(Want to upload larger file but facing an error during posting see how to uploading larger file through file upload in asp.net web config setting)

Save posted file and validate mime type as well as extensions code

protected void btnUpload_Click(object sender, EventArgs e)
{
 string fileName = fuFile.PostedFile.FileName;
 string fileExtension=System.IO.Path.GetExtension(fileName);
 string fileMimeType = fuFile.PostedFile.ContentType;
 int fileLengthInKB = fuFile.PostedFile.ContentLength / 1024;

 string[] matchExtension = { ".jpg", ".png", ".gif" };
 string[] matchMimeType = { "image/jpeg", "image/png", "image/gif" };

 if (fuFile.HasFile)
 {
      
   if (matchExtension.Contains(fileExtension) && matchMimeType.Contains(fileMimeType))
   {
     if (fileLengthInKB <= 1024)
     {
        fuFile.SaveAs(Server.MapPath(@"UserImages/" + fileName));
        Response.Write("File Uploaded Successfully");
     }
     else
     {
         //Please choose a file less than 1MB
     }

   }
   else
   {
       //Please choose only jpg, png or gif file.
   }
 }
 else
 {
     //Please choose a file.
 }
}

Aspx :-


<asp:FileUpload runat="server" ID="fuFile" />
<asp:Button runat="server" ID="btnUpload" Text="Upload" onclick="btnUpload_Click"/>


Recent Article