如何检查上传的文件格式是否正确?

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

我使用 C# 和 asp.net

我创建了一个带有 Web 表单的网页,您可以在其中输入信息以提交。我的页面上还有一个文件上传:<asp:FileUpload ID="FileUploadPassfoto" runat="server"/> 在我后面的 c# 代码中,我编写了一个 IF-Loop,它检查是否有东西被上传。像这样:

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;
}

它的作用是:正如我所说,它会检查是否上传了某些内容。如果没有上传任何内容,将显示 ErrorLabel,以便用户知道他忘记上传了。

我也想检查一下,上传的文件是不是图片。更清楚地说,我只想接受 .jpg/.bmp 和 .gif。如果上传了错误的格式,我也想显示我的 ErrorLabel。

我真的不知道该怎么做,你能帮帮我吗?谢谢

    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!";
    }

希望对你有更多帮助....

这是 David 在评论中发布的 link 的简化版本。

HttpPostedFile file = FileUploadPassfoto.PostedFile;
if (file.ContentType == "image/x-png" || file.ContentType == "image/pjpeg" || file.ContentType == "image/jpeg" || file.ContentType == "image/bmp" || file.ContentType == "image/png" || file.ContentType == "image/gif")
{
    // it is an image
}