Validate uploaded file extension

后端 未结 2 1042
逝去的感伤
逝去的感伤 2021-01-25 04:47

Uploading files works fine but now I\'m trying to validate file extensions and looks like there\'s some interference between FileUpload1 and FileUpload2

相关标签:
2条回答
  • 2021-01-25 05:11
    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))
    {
     //..........
    }
    

    or use RegularExpressionValidator:

    <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>
    
    0 讨论(0)
  • 2021-01-25 05:15

    are you uploading both files at the same time, or only one at a time? if it is only one at a time, then one of those values is always going to be false.

    You are also adding a period in front of your validPhotoFile and validPDFFile, change your code like this.

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题