Appending files to file input in Rails

1.9k Views Asked by At

I wish to upload multiple files using Paperclip in Rails. I have created a page that uploads the multiple files selected at a time. Now I wish to select more files using same file field and upload the files that are selected before and currently selected.

Following in my file_field:

    <div class="queue-empty">
      <span class="btn btn-primary btn-file">
        <span class="fileinput-new">Click to Browse</span>
          <%= photo.file_field :image,multiple: true,id: "File-Upload"%>
        </span>
    </div>

How can I append files to this file field without losing previously selected files?

1

There are 1 best solutions below

0
Liuda On

I've had the same problem, used Carrierwave, but I think it doesn't matter here as all was done on client side with jQuery. So, what I've done was creating an empty array:

data = [];

pushed uploaded file to array on file input change:

$('#File-Upload input[type=file]').change(function(e){
  var files = $('[type="file"]').get(0).files;
//checking if it was multiple files upload 
  if (!!$(this).prop('files') && $(this).prop('files').length > 1) { /
    files_array = $(this)[0].files //creating array of uploaded files
    $.each(files_array, function(indx, file){//iterate over this array, pushing files one by one 
      data.push(file)
    })
  }
  else {
    data.push($(this)[0].files[0]);// single file, just uploading 
  }
});

And then, when you have array of FileList objects, you can form FormData object and pass it on submit, like that:

 $(document).on('click', '.some-form input[type=submit]', function(e){
      e.preventDefault();
      formdata = new FormData();
      $.each(data, function(i, file) {
       formdata.append('files' + i, file);
     });
  //if you need to pass other parameters from your form you can do like this:
  //var other_data = $('.some-form').serializeArray();
  // $.each(other_data,function(key,input){
  //  formdata.append(input.name,input.value);
  //  });
  // ... some ajax call goes here
 });

Here is fiddle: https://jsfiddle.net/rp4kup3o/