如何使用primefaces在apache tomcat中上传文件?

时间:2014-12-03 07:07:19

标签: tomcat jsf-2 primefaces

我想知道当我们使用primefaces并使用apache tomcat服务器上传文件时会发生什么。据我所知,在将其上传到系统之前,tomcat暂时存储在某个地方。如果上传成功,我们能否在该临时文件夹中看到?如果文件大小较大,则会抛出这样的错误。

SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/maintenance] threw                 exception
java.io.IOException: Processing of multipart/form-data request failed. No space left on device

有任何帮助吗? 提前谢谢。

P.S我正在使用Unix

1 个答案:

答案 0 :(得分:1)

我使用apache tomcat,这对我来说很好用:

表单必须为enctype="multipart/form-data,并在web.xml

中添加
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</param-value>
</context-param>

 <filter>
  <filter-name>PrimeFaces FileUpload Filter</filter-name>
  <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>PrimeFaces FileUpload Filter</filter-name>
  <servlet-name>Faces Servlet</servlet-name>
  <dispatcher>FORWARD</dispatcher>
</filter-mapping>

在xhtml文件中:

<h:form enctype="multipart/form-data" id="upload">
<p:fileUpload id="fileUpload" fileUploadListener="#{uploadParcelBean.handleFileUpload}" mode="advanced"
        allowTypes="/(\.|\/)(gif|jpe?g|png|bmp|pdf|doc|docx|xls|xlsx|txt)$/"        
        description="Select File"        
        label="Select File" uploadLabel="Upload" cancelLabel="Cancel"        
        validatorMessage="Invalid Format."      
        dragDropSupport="true"      
        multiple="true"      
        update="growl fileList"
        disabled="false"/>
</h:form>

在bean方面,您可以处理上传的文件:

public void handleFileUpload(FileUploadEvent event) {    
    try {        
    copyFile(event.getFile().getFileName(), event.getFile().getInputstream());             
    //other logics
    }
    catch(IOException e){
     e.printStackTrace();           
    }

复制方法类似于:

public void copyFile(String fileName, InputStream in) {

      String destination="C:\\uploads\\";
      try {

              // write the inputStream to a FileOutputStream

             File theDir = new File(destination);            
             if(!theDir.exists())
             {
                 try {
                    theDir.mkdir();

                } catch (Exception e) {
                    e.printStackTrace();
                }

             }            


    OutputStream out = new FileOutputStream(new File(destination + fileName));


              int read = 0;
              byte[] bytes = new byte[1024];

              while ((read = in.read(bytes)) != -1) {
                  out.write(bytes, 0, read);
              }

              in.close();
              out.flush();
              out.close();           

              } catch (IOException e) {
              System.out.println(e.getMessage());
              }
  }