Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrimeFaces number of files in FileUpload

I'm very new to PrimeFaces components. I have a FileUpload (multiple files uploaded) and I want to know if there's a way to know how many files are in the upload component before uploading them. What I need is to upload 1 to 6 files and just after the 6th is uploaded process the all the files. Any idea on how can I achieve this is very welcome.

Cheers

UPDATE Already tried with oncomplete but it does not help me 'cause this event is executed every time a file is uploaded not 'till all files are.

like image 813
BRabbit27 Avatar asked Dec 20 '11 22:12

BRabbit27


1 Answers

Ok, this is pretty old thread but I've found straitforward way to determine the number of files been uploaded.

p:fileUpload widget has an array with meta-info about selected files. By passing the length of this array to your bean you will obtain the total number of files.

There is a problem though: p:fileUpload doesn't submit the surrounding form, so I had to put invisible button along with the h:inputHidden to pass the number of files from JavaScript to ManagedBean:

<h:form id="importDlgForm">
    <p:fileUpload id="importFile" widgetVar="importFile" fileUploadListener="#{importDialogView.importFile}"
                      mode="advanced" multiple="true"
                      onstart="$('#importDlgForm\\:file_number_input').val(PF('importFile').files.length);
                      $('#importDlgForm\\:submit_btn').click();"/>
    <h:inputHidden id="file_number_input" value="#{importDialogView.importFileNumber}"/>
    <p:commandButton id="submit_btn" style="display: none"/>
</h:form>

I also had to use AtomicInteger in order to track processed files, as p:fileUpload uses multiple threads to upload files by default.

private final AtomicInteger atomicImportFileNumber = new AtomicInteger();
private Integer importFileNumber;

public Integer getImportFileNumber() {
    return importFileNumber;
}

public void setImportFileNumber(Integer importFileNumber) {
    this.importFileNumber = importFileNumber;
    atomicImportFileNumber.set(importFileNumber);
}

public void importFile(FileUploadEvent event) {
    // common file upload stuff
    if (atomicImportFileNumber.decrementAndGet() == 0) {
        // part to execute only when all files have been uploaded   
    }
}
like image 166
Aleksandr Erokhin Avatar answered Sep 23 '22 21:09

Aleksandr Erokhin