Thursday, 8 May 2014

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

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
  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"/>

No comments:

Post a Comment