Identifying each field in Multiple File upload

2019-03-05 02:53发布

问题:

When trying to upload multiple files with Struts2 using ArrayList, how to identify each field?

For example, if I have two file fields, File1 and File2 and on the client side, I choose to upload only File2, Struts 2 only creates one element in the list and I am not able to correctly map File1 as empty and File2 with the uploaded file.

Is there any identifier I can use here?

回答1:

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).



回答2:

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