1

I am using FormData to upload multiple files in my grails project.The files needs to be uploaded via Ajax. I have used following code for ajax upload. But in controller, I get the params as [object FileList]. How do I get files from this object. Is there any way to change this object to multipart?

jQuery('#file-save').click(function() {
  if (jQuery('#form input[type="file"]')) {
    var form = jQuery("#form").find('input[type="file"]');

    var picData = new FormData();
    picData.append('userFiles', form.get(0).files);
    picData.append('userId', '$usrId');

    jQuery.ajax({
      url: '/file/upload',
      type: 'post',
      dataType:'json',
      data: picData,
      enctype: "multipart/form-data",
      contentType: false,
      processData: false,
      success: function(data) {
        console.log("success");
      }
    });
  }
});
The controller code is:
def upload(){
    def userId = params.userId
    def inputFile = params.userFiles
    println(inputFile)
    inputFile.each{i,j->
        println(i)
        println(j)
    }
}

When I debug, I get params.userFiles : "[object FileList]". Any insights would be appreciated.

Prakash
  • 368
  • 5
  • 16
  • How to upload a file and read in a file input check this link: http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload?rq=1 – Juniar Mar 21 '17 at 03:59
  • The above code works well. For single file upload, I get multipart data which I can easily save to external folder. But for multiple file uploads, I get [object FileList]. I need a way to parse this. – Prakash Mar 21 '17 at 04:22

1 Answers1

1

You most likely need to loop through the files client side, adding the same key for each one

var picData = new FormData();
// loop through form.get(0).files
picData.append('userFiles', file);
// end loop
picData.append('userId', '$usrId');
James Kleeh
  • 12,094
  • 5
  • 34
  • 61