日期:2014-05-16  浏览次数:20292 次

使用primefaces的JSF做一个文件上传功能所遇到的问题(2)
   经过了两天的折磨,上传文件的功能终于得到了解决,算是给自己一个学习的机会,使用primefaces的<p:fileUpload>功能上传文件。

   1.jar包的引入, 在你的pom.xml文件里面导入 需要以下的几个文件
  
     primeface-2.2.RC2.jar 
     jsf-api-2.0.2.jar 
     jsf-impl-2.0.2.jar
     el-api-2.2.jar
     el-impl-2.2.jar
     commons-io-1.4.jar
     commons-fileupload-1.2.jar
   


   2.web.xml文件的配置,因为是在一个已有的工程里面进行

  
   	<!-- File Upload -->
	<filter>
		<filter-name>PrimeFaces FileUpload Filter</filter-name>
		<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>

		<init-param>
		<param-name>thresholdSize</param-name>
		<param-value>2097152</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>PrimeFaces FileUpload Filter</filter-name>
		<servlet-name>faces-servlet</servlet-name>
	</filter-mapping>

         <servlet>
		<servlet-name>faces-servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>faces-servlet</servlet-name>
		<url-pattern>*.xhtml</url-pattern>
	</servlet-mapping>
   


   3.界面的代码
  
   <h:form id="uploadForm">
      <p:fileUpload id="upload" fileUploadListener="#{blackListImportBean.handleFileUpload}"
			multiple="true" allowTypes="*.xls;*.xlsx" description="*.xls;*.xlsx" sizeLimit="10000000000"/>

     </h:form>
   


    4.对应的java代码
   
    public void handleFileUpload(FileUploadEvent event)
    {
		System.out.println("Handling Upload: " + event.getFile());
		UploadedFile upload = event.getFile();
		FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_INFO, "File Uploaded", "This file is " + upload));
		//do whatever here....
     }
    


    上面的代码和配置是我在项目中运行并测试通过的,应该不会有其他的问题