【问题标题】:Validate uploaded file extension验证上传的文件扩展名
【发布时间】:2014-11-06 13:39:34
【问题描述】:

上传文件工作正常,但现在我正在尝试验证文件扩展名,看起来有一些干扰 在FileUpload1FileUpload2 之间。

FileUpload1 用于上传 .jpg 或 .png 图片,FileUpload2 用于上传 .pdf 文件。

这是在BtnInsert_Click 事件上执行的代码:

protected void BtnInsert_Click(object sender, EventArgs e)
{
    string[] validPhotoFile = { ".jpg", ".png" };
    string validPDFFile = ".pdf";

    string photoExt = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
    string pdfExt = System.IO.Path.GetExtension(FileUpload2.PostedFile.FileName);

    bool isValidPhotoFile = false;
    bool isValidPDFFile = false;

    for (int i = 0; i < validPhotoFile.Length; i++)
    {
        if (photoExt == "." + validPhotoFile[i])
        {
            isValidPhotoFile = true;
            break;
        }
    }

    for (int i = 0; i < validPDFFile.Length; i++)
    {
        if (pdfExt == "." + validPDFFile[i])
        {
            isValidPDFFile = true;
            break;
        }
    }

    if (!isValidPhotoFile)
    {
        PhotoErrorMessage.Text = "Upload .jpg or .png image!";
    }

    if (!isValidPDFFile)
    {
        PDFErrorMessage.Text = "Upload .pdf file!";
    }

    else
    {
        string photoFilPath = Path.GetFileName(FileUpload1.PostedFile.FileName.ToString());
        string pdfFilPath = Path.GetFileName(FileUpload2.PostedFile.FileName.ToString());

        string photoPath = Server.MapPath(@"~/PDFCover/" + fotoFilPath);
        string pdfPath = Server.MapPath(@"~/PDF/" + pdfFilPath);

        FileUpload1.PostedFile.SaveAs(photoPath);
        FileUpload2.PostedFile.SaveAs(pdfPath);

        SqlCommand cmd = new SqlCommand("INSERT INTO Book(Title,Content...) VALUES ('" + TextBox1.Text
            + "','" + TextBox2.Text + ... + "','" + "~/PDFCover/" + photoFilPath
            + "','" + "~/PDF/" + pdfFilPath + "')", con);

        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
}

现在,即使我选择上传有效文件,它也会显示标签错误消息以上传有效文件。

【问题讨论】:

  • 是同时两个文件。在这种情况下,图像和 pdf 文件。
  • 扩展不是验证文件类型的方法。如果我使用“.jpeg”,甚至根本没有扩展名怎么办?正确的方法是解析文件,尽管在运行时成本更高。事实上,我经常发现有必要解析上传到服务器的图像文件,以缩小它们,例如,如果用户上传了一个 41 兆像素的文件作为个人资料图片。
  • @Kris 并不昂贵,因为 jpg、png 和 pdf 有自己的文件头格式,可以让您识别 8 到 20 个字节的文件。
  • @PTwr 是的。再说一次,“完整解析”是更彻底的验证。就像我说的那样,我经常需要做一个完整的解析,特别是对于图像,以缩小它们。
  • @KrisVandermotten 如果用户懒得在上传之前缩小图片,你可以试试tricking their machine in doing this job ;)

标签: c# asp.net validation


【解决方案1】:

您是同时上传两个文件,还是一次只上传一个?如果一次只有一个,那么其中一个值总是错误的。

您还在您的 validPhotoFile 和 validPDFFile 前面添加一个句点,像这样更改您的代码。

for (int i = 0; i < validPhotoFile.Length; i++)
{
    if (photoExt == validPhotoFile[i]) // remove the period here it is already in your variables above
    {
        isValidPhotoFile = true;
        break;
    }
}

for (int i = 0; i < validPDFFile.Length; i++)
{
    if (pdfExt == validPDFFile[i]) // remove the period here it is already in your variables above
    {
        isValidPDFFile = true;
        break;
    }
}

【讨论】:

    【解决方案2】:
    bool CheckFileType(string fileName)
    {
        string ext = Path.GetExtension(fileName);
        switch (ext.ToLower())
        {
            case ".gif":
                return true;
            case ".jpg":
                return true;
            case ".jpeg":
                return true;
            case ".png":
                return true;
            default:
                return false;
        }
    }
    
    if (CheckFileType(fuImage.FileName))
    {
     //..........
    }
    

    或使用正则表达式验证器:

    <asp:RegularExpressionValidator 
         ID="regexValidateImageFil" runat="server" ControlToValidate="fuImage" 
         ErrorMessage="file type not allow." 
         ValidationExpression="^([0-9a-zA-Z_\-~ :\\])+(.jpg|.JPG|.jpeg|.JPEG|.bmp|.BMP|.gif|.GIF|.png|.PNG)$"></asp:RegularExpressionValidator>
    

    【讨论】:

      猜你喜欢
      • 2011-05-13
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 2015-06-29
      • 1970-01-01
      • 2018-11-26
      相关资源
      最近更新 更多