【问题标题】:Appending files to file input in Rails在 Rails 中将文件附加到文件输入
【发布时间】:2017-03-08 06:38:41
【问题描述】:

我希望在 Rails 中使用 Paperclip 上传多个文件。我创建了一个页面,可以一次上传选择的多个文件。现在我希望使用相同的文件字段选择更多文件并上传之前选择和当前选择的文件。

在我的文件字段中:

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

如何在不丢失之前选择的文件的情况下将文件附加到此文件字段?

【问题讨论】:

    标签: ruby-on-rails append filefield photo-upload


    【解决方案1】:

    我也遇到过同样的问题,使用了 Carrierwave,但我认为这并不重要,因为所有操作都是在客户端使用 jQuery 完成的。 所以,我所做的是创建一个空数组:

    data = [];
    

    在文件输入更改时将上传的文件推送到数组:

    $('#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 
      }
    });
    

    然后,当您拥有 FileList 对象数组时,您可以形成 FormData 对象并在提交时将其传递,如下所示:

     $(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
     });
    

    这里是小提琴:https://jsfiddle.net/rp4kup3o/

    【讨论】:

      猜你喜欢
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 2017-03-20
      • 2011-11-15
      • 1970-01-01
      • 1970-01-01
      • 2019-10-21
      相关资源
      最近更新 更多