Validating dimensions of an uploaded image in file upload listener in PrimeFaces

扶醉桌前 提交于 2019-12-06 10:23:02

Your concrete problem is caused because the upload action took place in a different HTTP request than the save action. You first choosed the file and then pressed Upload (request #1) and then the Save button (request #2), right? The network monitor in browser's builtin developer toolset (press F12) should also confirm it. The FacesContext#validationFailed() is in essence request scoped, like the FacesContext itself. So, when you set it during the request which invokes the upload action, then it's just "reset" during the request which invokes the save action.

This is indeed somewhat awkward. As the <p:fileUpload mode="advanced"> doesn't support Validators, as you already found out, there's not really a clean solution to this problem. You should be fiddling with a view scoped bean property to maintain the validation state across the requests on the same view.

private boolean validationFailed;

public void fileUploadListener(FileUploadEvent event) throws IOException {
    // ...
    validationFailed = !Utility.validateImageDimensions(bytes);

    if (validationFailed) {
        // Add message.
    }
    else {
        // Process upload.
    }
}

public void insert() {
    if (validationFailed) {
        // Add message.
    }
    else {
        // Process insert.
    }
}

By the way, I'd rather not set those messages as FATAL, but as ERROR. The enduser is namely capable of fixing it all by itself.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!