如果声明似乎没有评估错误

时间:2015-05-18 23:23:56

标签: java if-statement boolean-logic

目标:用户上传图片,验证者检查以确保它是用户上传的图片文件,如果不是图片则返回消息,如果不是,则返回消息。

问题:单击“上载”按钮时,无论上载的文件是图像还是图像,都始终返回验证器消息。

焦点区域:在Validator类中,行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);
        }

这是如何引起的?如何解决?

1 个答案:

答案 0 :(得分:1)

你的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)并且可能强制执行文件大小限制...

或者使用HashSet:

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