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

时间:2016-08-05 12:45:58

标签: c# asp.net file-upload format binaryreader

我使用c#和asp.net

我创建了一个带有网络表单的网页,您可以在其中输入您的信息以便提交。我的页面上还有一个文件上传:<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。

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

2 个答案:

答案 0 :(得分:2)

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

希望它能帮到你......

答案 1 :(得分:1)

以下是David在评论中发布的链接的简化版本。

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
}
相关问题