如何使用<p:fileupload> </p:fileupload>限制允许上载的文件数

时间:2012-09-29 18:55:00

标签: file-upload jsf-2 primefaces

如何在JSF 2 + primefaces应用程序中限制允许上传的文件数。属性'filelimit'在primeface 3.3中有,但我使用的是primefaces 3.4

1 个答案:

答案 0 :(得分:10)

看起来已在问题3618

中删除了fileLimit选项

如评论中所述,使用支持bean中的计数器并丢弃额外的文件或添加FacesMessage以通知用户已达到最大fileLimit。

代码示例:

@ManagedBean
@ViewScoped
public class FileUploadController {

    private final static int MAX_NUM_FILES = 3;
    private List<UploadedFile> uploadedFiles;
    private int counter = 0;

    @PostConstruct
    public void init() {
        uploadedFiles = new ArrayList<UploadedFile>();
    }


    public void handleFileUpload(FileUploadEvent event) {
        if (counter < MAX_NUM_FILES) {
            uploadedFiles.add(event.getFile());
            FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            counter ++;       
        }
        else {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "File Upload Limit Reached ", event.getFile().getFileName() + " is not uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }

    }
}