【问题标题】:if statement does not seem to ever evaluate falseif 语句似乎永远不会评估为 false
【发布时间】:2015-05-18 23:23:55
【问题描述】:

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

问题:当点击上传按钮时,无论上传的文件是图片还是非图片,都会返回验证器消息。

重点领域: 在 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);
        }

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

【问题讨论】:

  • 喝杯好咖啡,再看一遍。将每个单独的条件替换为“真”或“假”。到底看起来还好吗?
  • 出于调试目的,包含实际的partValueContentType 值。即FacesMessage msg = new FacesMessage("File is not an image.", "Acceptable image types (jpeg, jpg, gif, png) but got " + partValueContentType);
  • @DilumRanatunga:你还需要一杯好咖啡。
  • 大声告诉自己 if 语句中的子句是做什么的。什么时候是真的?
  • @BalusC - 哈哈,你是对的。那个结构看起来很奇怪,但我没有深入挖掘......

标签: java if-statement boolean-logic


【解决方案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);
}

【讨论】:

  • 或者只是检查它是否以image/开头。另见 a.o. stackoverflow.com/questions/4169713/…
  • 这是真的,但这个答案更接近手头的问题 - OP 应该遵循您提供的链接以获得更好的实施。
  • 嘿@justderb。我喜欢您提供的 HashSet 示例,一旦我使用我正在开发的笔记本电脑,就会使用它。我同意应该检查该文件以确保它确实是一个图像类型的文件。这就是我使用此代码的原因。 getContentType() 方法不是一种有效的方法吗?如果没有,那你有什么建议?
  • 我建议走@BalusC 给你的路线。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
相关资源
最近更新 更多