primefaces上传

前端页面
<p:dataTable id="patchfiledatatable" var="patch" value="#{patchBean.files}" dynamic="true"
emptyMessage=""  paginator="true" rows="10" paginatorPosition="top">
<f:facet name="header">
<table>
<tr>
   <td style="text-align:left;width:85%;padding-top:5px;">查询结果</td>
   <td style="width:15%">
<p:commandLink
update=":uploadfile-model-form" oncomplete="patchInstallInfo.show();">
<h:graphicImage value="/images/icons/recover.gif"
styleClass="more-icon" title="导入补丁" />
<h:outputText value="导入补丁" />
</p:commandLink>
        <p:spacer width="10"/>
   </td>
</tr>
</table>
</f:facet>
</p:dataTable>

弹出框页面代码:

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<p:outputPanel>

<h:form id="uploadfile-model-form"  enctype="multipart/form-data">
<p:growl id="messages" showSummary="true" showDetail="true"/>
<p:dialog widgetVar="patchInstallInfo" id="uploadDiaId" header="导入补丁" modal="true" width="500" height="200" dynamic="false">
  <p:fileUpload fileUploadListener="#{patchBean.importPatchFile}" ajax="false" oncomplete="patchInstallInfo.hide()" multiple="true" update=":patchForm,:uploadfile-model-form:messages" />
</p:dialog>
</h:form>
</p:outputPanel>
</ui:composition>

后台代码
@ManagedBean(name = "patchBean")
@SessionScoped
public class TreeBean{ 
//导入补丁文件
public void importPatchFile(FileUploadEvent event){
FacesMessage msg = null;
try {
//新建文件输入流并对它进行缓冲
InputStream in = event.getFile().getInputstream();
BufferedInputStream inBuff = new BufferedInputStream(in);
// 新建文件输出流并对它进行缓冲
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
request.setCharacterEncoding("UTF-8");
File oldFile = new File(CURRENT_FILE_PATH+"\\"+event.getFile().getFileName());
if(!oldFile.exists()){
FileOutputStream output = new FileOutputStream(CURRENT_FILE_PATH+"\\"+event.getFile().getFileName());
BufferedOutputStream outBuff=new BufferedOutputStream(output);
// 缓冲数组         
byte[] b = new byte[1024 * 5];         
int len;        
while ((len =inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);   
}
// 刷新此缓冲的输出流
outBuff.flush();
inBuff.close();     
outBuff.close();      
output.close();  
in.close();
files.clear();
this.getSubFiles(CURRENT_FILE_PATH);
msg = new FacesMessage(FacesMessage.SEVERITY_INFO,"操作成功",null);
}else{
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"该文件已存在",null);
}
FacesContext.getCurrentInstance().addMessage("uploadfile-model-form:messages", msg);
} catch (Exception e) {
System.out.println("上传出异常了");
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"操作失败",null);
FacesContext.getCurrentInstance().addMessage("uploadfile-model-form:messages", msg);
e.printStackTrace();
}
}
}

你可能感兴趣的:(上传,导入,primefaces,fileUpload用法)