primefaces5 jsf2多次上传e扫描元素

时间:2015-11-13 10:43:40

标签: jsf file-upload jsf-2 primefaces multi-upload

大家好,我在PrimeFaces / Jsf2上传了更多文件时遇到了问题

我看到http://www.primefaces.org/showcase/ui/file/upload/multiple.xhtml

当方法拦截我设置的事件

UploadedFile fileUpload = event.getFile();

我希望扫描使用List

的实现上传的每个文件
    InputStream input;
    input = event.getFile().getInputstream();
    pojo.setFileInputStream(input);
    input.close();
    fileTableList.add(pojo);

但最大的问题是这个列表只包含一个上传的文件。 如何从UploadedFile事件中上传每个文件?

怎么了? 谢谢你的回答

1 个答案:

答案 0 :(得分:0)

  

但最大的问题是这个列表只包含一个文件   上传。如何从UploadedFile上传每个文件   事件

除非您使用最小可重复的示例明确说明,否则无法使用最少可能的依赖项/资源来复制此项。

创建如下所示的实用程序类(该类完全取决于要求)。

public class FileUtil implements Serializable {

    private InputStream inputStream; // One can also use byte[] or something else.
    private String fileName;
    private static final long serialVersionUID = 1L;

    public FileUtil() {}

    // Overloaded constructor(s) + getters + setters + hashcode() + equals() + toString().
}

托管bean接收多个文件:

@Named
@ViewScoped
public class TestBean implements Serializable {

    private List<FileUtil> fileList;
    private static final long serialVersionUID = 1L;

    public TestBean() {}

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

    public void fileUploadListener(FileUploadEvent event) throws IOException {
        UploadedFile file = event.getFile();
        FileUtil fileUtil = new FileUtil();
        fileUtil.setInputStream(file.getInputstream());
        fileUtil.setFileName(file.getFileName());
        fileList.add(fileUtil);
    }


    // Bound to a <p:commandButton>.

    public void action() {
        for (FileUtil fileUtil : fileList) {
            System.out.println(fileUtil.getFileName());
        }

        // Use the list of files here and clear the list afterwards, if needed.
        fileList.clear();
    }
}

仅为了演示而仅包含<p:fileUpload><p:commandButton>的XHTML文件。

<h:form id="form">
    <p:fileUpload id="fileUpload"
                  mode="advanced"
                  fileLimit="5"
                  multiple="true"
                  allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
                  sequential="true"
                  process="@this"
                  fileUploadListener="#{testBean.fileUploadListener}">
    </p:fileUpload>

    <p:commandButton value="Submit"
                     process="@this"
                     update="fileUpload"
                     actionListener="#{testBean.action}"/>
</h:form>

如果您需要byte[]代替InputStream,那么只需将private InputStream inputStream;课程中的FileUtil更改为byte[],然后再使用

byte[] bytes = IOUtils.toByteArray(uploadedFile.getInputstream());

InputStream中提取字节数组(其中IOUtils来自org.apache.commons.io。您也可以通过编写几行代码手动完成。)

您也可以构建List<UploadedFile>而不创建像FileUtil这样的附加类,但是这样做会强制要求服务层上的PrimeFaces依赖(不应该发生),如果你发生了在您的应用程序中使用该层,因为UploadedFile是PrimeFaces工件。毕竟它完全取决于要求。

相关问题