我想使用 PrimeFaces 和 ManagedBean 上传文件。我想p:fileUpload
与 mode="simple" 一起使用。
XHTML 代码:
<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()" />
托管豆:
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);
}
}
}
}
我的问题是,我单击了命令按钮,并且未调用支持 bean 中的方法。如果我使用ajax="false"
该方法被调用,但页面被刷新。
我怎样才能使用ajax="true"
和<p:fileUpload>
在一起?