Java if语句似乎从未计算过false
目标:用户上传图像,验证器检查以确保它是用户上传的图像文件,如果不是图像则返回消息,如果是则不返回消息 问题:单击上载按钮时,无论上载的文件是否为图像,都会返回验证程序消息 焦点区域:在Validator类中,行Java if语句似乎从未计算过false,java,if-statement,boolean-logic,Java,If Statement,Boolean Logic,目标:用户上传图像,验证器检查以确保它是用户上传的图像文件,如果不是图像则返回消息,如果是则不返回消息 问题:单击上载按钮时,无论上载的文件是否为图像,都会返回验证程序消息 焦点区域:在Validator类中,行System.out.println(partValueContentType)已将内容类型写入控制台,例如图像/jpeg,但在if语句中对其进行测试时,它似乎根本不会评估内容类型 String partValueContentType = part.getContent
System.out.println(partValueContentType)
已将内容类型写入控制台,例如图像/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);
}
String partValueContentType=part.getContentType();
System.out.println(partValueContentType);
Set acceptedMimeTypes=newhashset(Arrays.asList(“image/jpeg”、“image/jpg”、“image/gif”、“image/png”));
如果(!AcceptedMitypes.contains(partValueContentType))
{
FacesMessage msg=新的FacesMessage(“文件不是图像。”,
“可接受的图像类型”+Arrays.toString(acceptedMimeTypes.toArray());
消息设置严重性(FacesMessage.SEVERITY_错误);
抛出新的验证异常(msg);
}
喝一杯好咖啡,然后再看一遍。用“真”或“假”替换每个单独的条件。最后看起来还好吗?出于调试目的,请包含实际的partValueContentType
值。i、 e.FacesMessage msg=newfacesmessage(“文件不是图像。”,“可接受的图像类型(jpeg、jpg、gif、png),但获得”+partValueContentType)代码>@DilumRanatunga:你还需要一杯好咖啡。大声告诉自己if语句中的子句做了什么。什么时候是真的?@BalusC-LOL你是对的。这个结构看起来很奇怪,但我没有深入挖掘……或者只是检查它是否以image/
开头。另请参见a.o.这是正确的,但这个答案更接近于手头的问题-OP应该遵循您提供的链接,以便更好地实现。嘿@justderb。我喜欢您提供的HashSet示例,并且在我使用正在开发的笔记本电脑时将使用它。我同意应该检查该文件,以确保它确实是图像类型的文件。这就是我使用此代码的原因。getContentType()方法不是一种有效的方法吗?如果没有,那么你有什么建议?我建议你走巴卢斯给你的路线。