我有一个 UI,可以选择将多个特定性质的文档上传到一个问题。我能够在整个应用程序的其余部分毫无问题地上传单个文件。
环境
- Tomcat 7.0.x
- Mojarra JSF 实现 2.1.3 (20110908-FCS)
- JSF 2.1 和 Primefaces 2.2
- Apache 战斧。
代码解释
这是循环遍历文档信息实体的代码。这些实体要么是来自数据库的记录,要么是占位符。实体将具有指向数据库中项目(如果存在)的 ID,否则将为 0,表示它是占位符并且可以上传文件。
在占位符的情况下,有一个上传按钮,它会弹出一个 Primefaces 对话框,其中有一个战斧文件上传组件。
代码
这是 JSF 代码:
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:t="http://myfaces.apache.org/tomahawk"
xmlns:p="http://primefaces.prime.com.tr/ui"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<ui:repeat var="extDoc" value="#{reportBean.externalDocs}"
varStatus="extDocIdx">
<!-- Display the document name -->
<h:outputText value="#{extDoc.name}"/>
<!-- if the document is not in the database, give the option to add it -->
<ui:fragment rendered="#{extDoc.id == 0}">
<!-- On click of the upload button, display the dialog -->
<h:commandButton value="Upload" type="button"
onclick="uploadDlg#{extDocIdx.index}.show()" modal="true"/>
<p:dialog header='Upload document for #{extDoc.name}'
modal="true" widgetVar="uploadDlg#{extDocIdx.index}"
width="650" minWidth="650">
Select the file to upload:
<!-- THIS IS WHERE THE PROBLEM IS -->
<t:inputFileUpload value="#{reportBean.uploadedFile}"/>
<br/>
<h:commandButton value="Submit"
action="#{reportBean.addExtDocument(extDoc.name, extDocIdx.index)}"/>
</p:dialog>
</ui:fragment>
<ui:fragment rendered="#{extDoc.id != 0}">
<!-- display a link to the uploaded file -->
</ui:fragment>
</ui:repeat>
以及 ReportBean 中的 uploadedFile 属性:
private UploadedFile uploadedFile;
public UploadedFile getUploadedFile() { return uploadedFile; }
public void setUploadedFile(UploadedFile value) { uploadedFile = value; }
public void addExtDocument(String name, int idx)
throws IOException
{
// access uploadedFile to persist the information
}
问题
我愚蠢地只有一个 uploadedFile 变量来处理上传文件的整个循环;因此,循环中的最后一项总是会覆盖其他项,因此无法上传除最后一项以外的任何内容。我显然需要为每次循环指定一个不同的 uploadedFile。我尝试使用 List
问题
所以问题是:我在 t:inputFileUpload 中包含什么样的 EL,我在 ReportBean 中使用什么样的属性来在我的 addDocument 方法中提供单独的 uploadedFile 实例?
最佳答案
您可以使用 List<UploadedFile>
或 UploadedFile[]
并使用大括号表示法访问各个项目,其中传递 <ui:repeat>
的当前索引如下:
<t:inputFileUpload value="#{reportBean.uploadedFiles[extDocIdx.index]}"/>
无论哪种方式,您都需要确保该属性已正确预初始化。 List
必须用 new ArrayList<>()
初始化并且数组必须预先初始化为正确的长度。 JSF/EL 不会为您预先创建它;它只是在给定的索引上设置给定的项目,仅此而已。在 null
上列表或数组,你只会面对 PropertyNotWritableException
在空数组或错误大小的数组上,您只会遇到 ArrayIndexOutOfBoundsException
.
关于ui :repeat 中的 JSF 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13051448/