验证上传的文件扩展名

use*_*489 3 c# asp.net validation

上传文件工作正常,但现在我试图验证文件扩展名,看起来像有之间的一些干扰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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Chư*_*iết 8

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))
{
 //..........
}
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)