0
votes

I've done this part of the form

<td>
   <h:form enctype="multipart/form-data">  
      <p:fileUpload fileUploadListener="#{uploadBean.handleFileUpload(event)}"  
                    mode="advanced"  
                    update="messages"   
                    multiple="true"  
                    sizeLimit="2000000"   
                    allowTypes="/(\.|\/)(pdf|doc?x|xls?x)$/"/>  
       <p:growl id="messages" showDetail="true"/>  
    </h:form>
</td> 

and this event handler in class:

    public class UploadBean {

    /** Creates a new instance of UploadBean */
    public UploadBean() {
    }
    private static final int BUFFER_SIZE = 6124;
    public void handleFileUpload(FileUploadEvent event) {

    ExternalContext extContext = FacesContext.getCurrentInstance().
                                 getExternalContext();
    File result = new File(extContext.getRealPath
     ("//WEB-INF//upload") + "//" + event.getFile().getFileName());

try {
    FileOutputStream fileOutputStream = new FileOutputStream(result);

    byte[] buffer = new byte[BUFFER_SIZE];

    int bulk;
    InputStream inputStream = event.getFile().getInputstream();
    while (true) {
      bulk = inputStream.read(buffer);
      if (bulk < 0) {
             break;
             }
      fileOutputStream.write(buffer, 0, bulk);
      fileOutputStream.flush();
      }

      fileOutputStream.close();
      inputStream.close();

      FacesMessage msg = new FacesMessage("Succesful", 
          event.getFile().getFileName() + " is uploaded.");
      FacesContext.getCurrentInstance().addMessage(null, msg);

      } catch (IOException e) {

      FacesMessage error = new FacesMessage("The files were not uploaded!");
      FacesContext.getCurrentInstance().addMessage(null, error);
      }
    }
}

Now the handling method I got it from a site. I am not sure why this is failing to upload. it looks okay to me. Maybe am missing something? so the control appears on my page and I can choose file, but then upload progress bar just proceeds fast...no growl notification shows and also no file uploaded of course. Thanks,

1

1 Answers

3
votes

From the docs (Assuming using Primefaces)
First thing to do is to configure the fileupload filter which parses the multipart request. FileUpload filter should map to Faces Servlet.

    <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>
    </filter-mapping>

Hope you are not missing this setting.

Also not sure whats event in your code

<p:fileUpload fileUploadListener="#{uploadBean.handleFileUpload(event)}" .....