在PrimeFaces中验证文件上传监听器中上传图像的尺寸 [英] Validating dimensions of an uploaded image in file upload listener in PrimeFaces

查看:153
本文介绍了在PrimeFaces中验证文件上传监听器中上传图像的尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用< p:fileUpload> 来上传图片,如下所示:

 < p:outputLabel for =txtCatImagevalue =#{messages ['category.image']}/> 

< p:fileUpload id =txtCatImagemode =advanced
dragDropSupport =truerequired =true
sizeLimit =1000000fileLimit =1
uploadLabel =#$ messages $'$'$'$'$' #{messages ['fileupolad.uploadLabel']}
allowTypes =/(\。| \ /)(gif | jpe?g | png)$ /
invalidFileMessage = {messages ['fileupolad.invalidFileMessage']}
invalidSizeMessage =#{messages ['fileupolad.invalidSizeMessage']}
fileLimitMessage =#{messages ['fileupolad.fileLimitMessage']}
fileUploadListener =#{categoryManagedBean.fileUploadListener}/>
< p:message for =txtCatImageshowSummary =false/>

actionListener =#{categoryManagedBean.insert}
value =#{messages [ button.save']}/>

fileUploadListener @ViewScoped 如下。

  //这只是一个实用程序方法,可以放在应用程序的任何地方。 
private static boolean validateImageDimensions(byte [] bytes)throws IOException {
BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(bytes));
返回bufferedImage.getHeight()> = 750 || bufferedImage.getWidth()> = 650;

$ b $ public void fileUploadListener(FileUploadEvent event)throws IOException {
UploadedFile uploadedFile = event.getFile();
byte [] bytes = IOUtils.toByteArray(uploadedFile.getInputstream()); $!
$ b $ if(!Utility.validateImageDimensions(bytes)){
FacesContext context = FacesContext.getCurrentInstance();
context.validationFailed();
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_FATAL,Message summary,Error message);
FacesContext.getCurrentInstance()。addMessage(event.getComponent()。getClientId(context),message);
}
else {//做点什么}
}

< p:commandButton> 的监听器如下所示,如果在 fileUploadListener )失败。

  public void insert(){$ b $ // //调用EJB与上传的文件一起插入新行。如果 if(!Utility.validateImageDimensions(bytes)),则返回





$ )
被评估为true,那么< p:commandButton> insert()上面的code>方法)不应该被调用,而是被调用,这种验证意味着根本没有任何效果。如前所述,PrimeFaces文件上传验证器不起作用。



我在这里做错了什么?什么是验证上传图片的尺寸的方法?

解决方案

您的具体问题是由于上传操作发生在不同于保存操作的HTTP请求。您首先选择了文件,然后按下上传(请求#1),然后按下 Save 按钮(请求#2),对不对?浏览器的内置开发者工具集(按F12)中的网络监视器也应该确认它。 FacesContext#validationFailed()本质上是request的作用域,就像 FacesContext 本身一样。所以,当你在调用上传动作的请求中设置它的时候,在调用保存动作的请求期间它只是重置。

这确实有些尴尬。由于< p:fileUpload mode =advanced> 不支持 Validator 发现,这个问题并不是一个干净的解决方案。您应该摆弄视图范围的bean属性,以维护同一视图上的请求的验证状态。

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

if(validationFailed){
//添加消息。
}
其他{
//处理上传。


$ b $ public void insert(){
if(validationFailed){
//添加消息。
}
else {
//处理插入。


$ / code $ / pre

顺便说一下,消息为 FATAL ,但是为 ERROR 。最终用户可以自行修复它。


I'm uploading images using <p:fileUpload> as follows.

<p:outputLabel for="txtCatImage" value="#{messages['category.image']}"/>

<p:fileUpload id="txtCatImage" mode="advanced" 
              dragDropSupport="true" required="true"
              sizeLimit="1000000" fileLimit="1" multiple="false" 
              cancelLabel="#{messages['fileupolad.cancelLabel']}"
              label="#{messages['fileupolad.label']}"
              uploadLabel="#{messages['fileupolad.uploadLabel']}" 
              allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
              invalidFileMessage="#{messages['fileupolad.invalidFileMessage']}"
              invalidSizeMessage="#{messages['fileupolad.invalidSizeMessage']}"
              fileLimitMessage="#{messages['fileupolad.fileLimitMessage']}"
              fileUploadListener="#{categoryManagedBean.fileUploadListener}"/>
<p:message for="txtCatImage" showSummary="false"/>

<p:commandButton id="btnSubmit" update="panel messages"
                 actionListener="#{categoryManagedBean.insert}"
                 value="#{messages['button.save']}"/>

fileUploadListener in the corresponding managed bean decorated with @ViewScoped is as follows.

//This is just a utility method and can be placed anywhere in the application.
private static boolean validateImageDimensions(byte[] bytes) throws IOException {
    BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(bytes));        
    return bufferedImage.getHeight()>=750 || bufferedImage.getWidth()>=650;
}

public void fileUploadListener(FileUploadEvent event) throws IOException {
    UploadedFile uploadedFile = event.getFile();
    byte[] bytes = IOUtils.toByteArray(uploadedFile.getInputstream());

    if(!Utility.validateImageDimensions(bytes)) {
        FacesContext context = FacesContext.getCurrentInstance();
        context.validationFailed();
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_FATAL, "Message summary", "Error message");
        FacesContext.getCurrentInstance().addMessage(event.getComponent().getClientId(context), message);
    }
    else {//Do something.}
}

The listener of <p:commandButton> is as follows which should not be invoked, if validation in fileUploadListener() fails.

public void insert() {
    //Code to invoke an EJB to insert a new row along with the uploaded file.
}

If if(!Utility.validateImageDimensions(bytes)) is evaluated to true then, the action listener of <p:commandButton> (the insert() method above) should not be invoked but it is invoked and this kind of validation implies no effect at all.

As already stated, PrimeFaces file upload validators don't work.

What am I doing wrong here? What is the way to validate dimensions of an uploaded image?

解决方案

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.

这篇关于在PrimeFaces中验证文件上传监听器中上传图像的尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆