if 语句似乎从未评估过 false

if statement does not seem to ever evaluate false

目标: 用户上传图像,验证器检查以确保它是用户上传的图像文件,如果不是图像,returns 消息,如果是的话就不会。

问题: 当点击上传按钮时,不管上传的文件是不是图片,总是返回验证器信息。

重点领域: 在验证器 class 中,行 System.out.println(partValueContentType); 已将内容类型写入控制台,例如。 image/jpeg,但在 if 语句中测试时,它似乎根本不评估内容类型。

        String partValueContentType = part.getContentType();
        System.out.println(partValueContentType);

        if (!partValueContentType.equals("image/jpeg")
                || !partValueContentType.equals("image/jpg")
                || !partValueContentType.equals("image/gif")
                || !partValueContentType.equals("image/png"))
        {
            FacesMessage msg = new FacesMessage("File is not an image.",
                    "Acceptable image types (jpeg, jpg, gif, png)");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(msg);
        }

这是怎么引起的,我该如何解决?

你的 if 语句有点不对:

String partValueContentType = part.getContentType();
System.out.println(partValueContentType);

if (!(partValueContentType.equals("image/jpeg")
        || partValueContentType.equals("image/jpg")
        || partValueContentType.equals("image/gif")
        || partValueContentType.equals("image/png")))
{
    FacesMessage msg = new FacesMessage("File is not an image.",
            "Acceptable image types (jpeg, jpg, gif, png)");
    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
    throw new ValidatorException(msg);
}

在验证方面,您可能需要检查文件本身以确保它确实是一张图片(它不是隐藏为 .jpeg 的 .zip)并且可能会强制执行文件大小限制...


或者使用哈希集:

String partValueContentType = part.getContentType();
System.out.println(partValueContentType);
Set<String> acceptedMimeTypes = new HashSet<>(Arrays.asList("image/jpeg", "image/jpg", "image/gif", "image/png"));

if (!acceptedMimeTypes.contains(partValueContentType))
{
    FacesMessage msg = new FacesMessage("File is not an image.",
            "Acceptable image types " + Arrays.toString(acceptedMimeTypes.toArray()));
    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
    throw new ValidatorException(msg);
}