Upload multiple files in Struts2 with Dropzone.js

Problem

When you use

<input type="file" name="file" multiple /> 

the files will all be sent with name="file", eg:

Content-Disposition: form-data; name="file"; filename="foo.jpg"
Content-Type: image/jpeg
...........
. ...
.......
Content-Disposition: form-data; name="file"; filename="bar.jpg"
Content-Type: image/jpeg
....
.
..
.......

and this is the right parameter Struts2 FileUpload Interceptor is expecting to receive, to work with a List<File> and the related List<String> for fileName and contentType.

When you use dropzone.js, instead, the filename will be altered to handle the multiple input client-side, by appending [] to it:

paramName: The name of the file param that gets transferred.
Defaults to file. NOTE: If you have the option uploadMultiple
set to true, then Dropzone will append [] to the name.

eg.

Content-Disposition: form-data; name="file[0]"; filename="foo.jpg"
Content-Type: image/jpeg
...........
. ...
.......
Content-Disposition: form-data; name="file[1]"; filename="bar.jpg"
Content-Type: image/jpeg
....
.
..
.......

Struts2 doesn’t like it at all.

Solution

Instead of messing with custom Interceptors and Converters, do a simple adjustment on the dropzone.js library you use for your Struts2 projects:

  1. Rename your dropzone.js to dropzone-struts2.js;
  2. Open the file and search "[" + n + "]" (line 866 in latest version)
  3. Change this line

    return "" + this.options.paramName + (this.options.uploadMultiple ? "[" + n + "]" : "");
    

    to this one

    return "" + this.options.paramName; //+ (this.options.uploadMultiple ? "[" + n + "]" : "");
    

Now it is Struts2 compliant, and will work with multiple uploads.

Leave a Comment