但最大的问题是这个列表只包含一个上传的文件。如何获取从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();
}
}
XHTML 文件仅包含 a<p:fileUpload>
和 a<p:commandButton>
只是为了演示。
<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>
不创建其他类的情况下构造 a ,FileUtil
如本示例中那样,但如果您碰巧在应用程序中使用该层,那么这样做会要求 PrimeFaces 依赖于服务层(这不应该发生),因为UploadedFile
它是 PrimeFaces 工件. 毕竟这完全取决于需求。