When trying to upload multiple files with Struts2 using ArrayList
, how to identify each field?
For example, if I have two file fields, File1
a
Use a List (or Map) of a custom object, containing your File, the fileName and the contentType (and eventually other fields). An JSP row corresponding element, to be clear.
I did like that (because I had many other fields too) and it works like a charm.
(this is not the only way, it is just one of the working ways that will become even more handy when you will need to handle additional fields too)
POJO
public class MyCustomRow implements Serializable {
private File fileUpload;
private String fileUploadFileName;
private String fileUploadContentType;
private String otherField1;
private String otherField2;
/* All Getters and Setters here */
}
in Action
private List<MyCustomRow> rows;
/* Getter and Setter ... */
in JSP
<s:iterator value="rows" status="row">
<s:file name="rows[%{#row.index}].fileUpload" />
<s:textfield name="rows[%{#row.index}].otherField1"/>
<s:textfield name="rows[%{#row.index}].otherField2"/>
</s:iterator>
File name and content-type will be automatically detected and populated by Struts2 (ensure you have FileUploadInterceptor in your stack).
Name each field with different names and create corresponding accessors to action properties. Then each of them will handle the name by OGNL and set corresponding properties. Try with different approach create list or map for the files indexed by iterator tag.
<iterator begin="0" end="50" status="status">
<s:file label="%{File + #status.index}" name="fileUpload[%{#status.index}]" size="40" />
</iterator>
<s:submit value="submit" name="submit" />
in action
private List<File> fileUpload = new ArrayList<File>();
also accessors should be for each property
then you will know which of them uploaded by checking the file at the list index. You could also try with the Map
.
<iterator begin="0" end="50" status="status">
<s:file label="%{File + #status.index}" name="fileUpload['%{#status.index}']" size="40" />
</iterator>
<s:submit value="submit" name="submit" />
in action
private Map<String, File> fileUpload = new HashMap<String, File>();
what is better suits your needs