2015-05-18 53 views
-1

目標:用戶上傳圖像,驗證程序檢查以確保它是用戶上傳的圖像文件,如果不是圖像則返回消息,如果不是是。if語句似乎沒有評估過false

Issue:單擊上傳按鈕時,無論上傳的文件是否爲圖像或圖像,始終返回驗證器消息。

重點領域:在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); 
     } 

這是怎麼造成的?我該如何解決?

+7

取一杯好咖啡,看看它AG艾因。用「true」或「false」替換每個單獨的條件。它到底看起來好嗎? – BalusC

+0

爲了調試目的,請包含實際的'partValueContentType'值。即'FacesMessage msg = new FacesMessage(「文件不是圖像」, 「可接受的圖像類型(jpeg,jpg,gif,png),但得到了」+ partValueContentType「;' –

+3

@DilumRanatunga:您還需要一杯咖啡。 – BalusC

回答

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); 
} 

在驗證方面,你可能要檢查的文件本身,以確保它是一個真正的圖片(這不是一個.zip隱藏爲.JPEG )也許執行文件大小限制......


或者用一個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); 
} 
+0

或者只是檢查它是否以'image /'開頭。另請參見ao http://stackoverflow.com/questions/4169713/how-to-check-a-uploaded-file-whether-it-is-a-image-或其他文件 – BalusC

+0

這是真的,但是這個答案更接近手頭的問題--OP應該遵循你提供的更好實現的鏈接。 – justderb

+0

嘿@justderb。我喜歡你提供的HashSet例子,並且會利用它一次我接觸到我正在開發的筆記本電腦,我同意應該檢查文件以確保它確實是一個圖像類型文件,這是我使用此代碼的原因。getContentType()方法不是有效的方法來做到這一點?如果不是,那麼你會建議什麼? –