Search code examples
c#asp.netfile-uploadformatbinaryreader

How do I check if the uploaded file has the right format?


I work with c# and asp.net

I created a webpage with a web form where you enter your information in order to submit it. There is also a file upload on my page: <asp:FileUpload ID="FileUploadPassfoto" runat="server"/> In my c# code behind i coded a IF-Loop which checks if something got uploaded. Like this:

if (FileUploadPassfoto.HasFile == true)
{
      HttpPostedFile file = FileUploadPassfoto.PostedFile;
      using (BinaryReader binaryReader = new BinaryReader(file.InputStream))
      {
          lehrling.passfoto = binaryReader.ReadBytes(file.ContentLength);
      }
      LabelPassfotoError.Visible = false;
}
else
{
     LabelPassfotoError.Visible = true;
     LabelError.Visible = true;
}

What it does is: As i said it checks if something got uploaded. If nothing got uploaded a ErrorLabel will be shown so the user knows he forgot to upload.

What i want to check too, is if the uploaded file is a image. To be more clear i only want to accept .jpg/.bmp and .gif. If a wrong format gets uploaded i want to display my ErrorLabel as well.

I dont really know how i should do this, can you please help me? Thank you


Solution

  •     protected void Button1_Click(object sender, EventArgs e)
        {
            string strFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
            string strFileWithoutExt = Path.GetFileNameWithoutExtension(strFileName);
            string strExtension = Path.GetExtension(strFileName);
            if (strExtension == ".jpg" || strExtension == ".bmp" || strExtension == ".gif")
            {
                string strImageFolder = "~/YourFilePath/";
                if (!Directory.Exists(Server.MapPath(strImageFolder)))
                    Directory.CreateDirectory(Server.MapPath(strImageFolder));
                string _strPath = Server.MapPath(strImageFolder) + strFileName;
                FileUpload1.PostedFile.SaveAs(_strPath);
                Label1.Text = "Upload status: File uploaded.";
            }
            else
                Label1.Text = "Upload status: only .jpg,.bmp and .gif file are allowed!";
        }
    

    Hope Its Help You much more....