How can I use <p: ​​fileUpload> with simple mode and ajax = "true"?

I want to upload a file using PrimeFaces and ManagedBean. I want to use p:fileUpload with mode = "simple".

XHTML Code:

  <p:fileUpload id="fileId" mode="simple" value="#{itemBean.upFile}" fileLimit="1" /> <p:commandButton ajax="true" value="Upload File" update="messagess" id="save-btn" actionListener="#{itemBean.fileUpload(itemBean.upFile,itemBean.hiddenFileName)}" process="@this" oncomplete="showImage()" /> 

ManagedBean:

 public void fileUpload(UploadedFile uploadFile, String hiddenKey) { String keyFileName = hiddenKey; boolean validFile = true; String expression = "([^\\s]+(\\.(?i)(gif|jpg|jpeg|gif|png|PNG|GIF|JPG|JPEG|bmp))$)"; if((uploadFile == null) ) { validFile = false; FacesMessage msg = new FacesMessage("Error! "+ "Please select an image."); FacesContext.getCurrentInstance().addMessage(null, msg); } else { System.out.println("going to file upload"+uploadFile.getFileName()+"---hiddenKey"+keyFileName); if((!uploadFile.getFileName().matches(expression)) ) { validFile = false; FacesMessage msg = new FacesMessage("Error! "+ uploadFile.getFileName() + " is not an image."); FacesContext.getCurrentInstance().addMessage(null, msg); } if(uploadFile.getSize() > 1000000) { validFile = false; FacesMessage msg = new FacesMessage("Error! "+ uploadFile.getFileName() + " size is too large."); FacesContext.getCurrentInstance().addMessage(null, msg); } if (validFile) { // Do what you want with the file try { //String extn =uploadFile.getFileName().substring(uploadFile.getFileName().lastIndexOf(".")); copyFile(uploadFile.getFileName(), uploadFile.getInputstream()); FacesMessage msg = new FacesMessage("Success! "+ uploadFile.getFileName() + " is uploaded."); FacesContext.getCurrentInstance().addMessage(null, msg); } catch (IOException e) { e.printStackTrace(); FacesMessage msg = new FacesMessage("Error! "+ uploadFile.getFileName()+ " not uploaded."); FacesContext.getCurrentInstance().addMessage(null, msg); } } } } 

My problem is that I pressed the button and the command method in the backup bean is not called. If I use ajax="false" , the method is called, but the page refreshes.

How can I use ajax="true" and <p:fileUpload> together?

+6
source share
1 answer

<p:fileUpload mode="simple"> does not support ajax. Sorry, but this is the end of the story.

If switching to ajax-compatible <p:fileUpload mode="advanced"> is actually not an option, it is best to upgrade to JSF 2.2 and use its new native component <h:inputFile> . It also appears in the default browser look'n'feel and is able to mimic the ajax experience with a hidden iframe trick.

See also:


Unrelated to a specific problem, these two arguments in your fileUpload() action method are completely unnecessary. Just

 action="#{itemBean.fileUpload}" 

with

 public void fileUpload() { // ... } 

works just as well once you remove the process="@this" attribute.

+7
source

Source: https://habr.com/ru/post/958132/


All Articles