1

I am trying to upload two zip files in formData.

The code look like that..

My form

<form id="fileForm">
  <input type="file" name="file" id="fileOne" />
  <input type="file" name="file" id="fileTwo" />
  <button id="btnUpload" type="button">Upload file</button>
</form>

jQuery + ajax

$(document).ready(function() {
  var imgContainer = $('#imgContainer');
  $('#btnUpload').click(function() {
    var formData = new FormData();
    $.each($("input[type=file]"), function(i, obj) {
      $.each(obj.files, function(j, file) {
        formData.append('file[' + j + ']', file);
        console.log(file);
      })
    });

    //Ajax call
    $.ajax({
      url: 'myUrl',
      type: "POST",
      data: formData,
      enctype: 'multipart/form-data',
      processData: false,
      contentType: false
    }).done(function(data) {
      imgContainer.html('');
      var img = '<img src="data:' + data.contenttype + ';base64,' +
        data.base64 + '"/>';

      imgContainer.append(img);
    }).fail(function(jqXHR, textStatus) {
      //alert(jqXHR.responseText);
      console.log('File upload failed ...');
    });
  });
});

My problem is that, When I receive the files in my controller, I get only one file.

This is What i get in fileMap, enter image description here one array has the value on another one is null.

My controller

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = {
  "application/json"
})
@ResponseBody
public String uploadFile(MultipartHttpServletRequest request,
  HttpServletResponse response) throws Exception {
  Map < String, MultipartFile > filesMap = new HashMap < String, MultipartFile > ();
  filesMap = request.getFileMap();
  System.out.println("filesMap :" + filesMap);
  return = "hello";
}

can anyone help me to debug the code. where am i doing mistake.

Varun
  • 4,342
  • 19
  • 84
  • 119

1 Answers1

0

An Old question, however, I would like to answer: The code is fine, however you need to use the index of the outer loop since the inner loop has one item therefore the key always enumerates to 0 overwriting the previous file in array i.e Replace the j index with i :

formData.append('file[' + i + ']', file);

Full excerpt:

$.each($("input[type=file]"), function(i, obj) {
      $.each(obj.files, function(j, file) {
        formData.append('file[' + i + ']', file); //replace j index here with i
        console.log(file);
      })
    });
Antony
  • 161
  • 3
  • 4