7

我正在尝试结合ng-file-uploadcarrierwave来上传多个文件,但服务器端的控制器只接收一个文件(所选文件的最后一项)。

客户端(参考

html

<button type="file" ng-model="files" ngf-select ngf-multiple="true">Upload</button>

js

var upload = function (files, content) {
    return Upload.upload({
        url: 'MY_CONTROLLER_URL',
        file: files, // files is an array of multiple files
        fields: { 'MY_KEY': 'MY_CONTENT' }
    }).progress(function (evt) {
        var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
        console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
    }).success(function (data, status, headers, config) {
        console.log('files ' + config.file.name + ' uploaded. Response: ' + data);
    }).error(function (data, status, headers, config) {
        console.log('error status: ' + status);
    });
};

console.log(files)打印Array[File, File, ...](浏览器:FireFox)。所以在客户端它确实得到了选定的文件。在ng-file-upload的GitHub页面上说它支持.html5

服务器端(参考

post_controller.rb

def create
    @post = Post.new(post_params)
    @post.attaches = params[:file]
    @post.save
    render json: @post
end

private
def post_params
    params.require(:post).permit(:content, :file)
end

where@post.attaches是帖子的附件,params[:file]由客户端通过filein 参数发送Upload.upload

我想将一组文件存储到@post.attaches中,但params[:file]只包含所选文件中的一个文件。 puts params[:file]印刷:

#<ActionDispatch::Http::UploadedFile:0x007fddd1550300 @tempfile=#<Tempfile:/tmp/RackMultipart20150812-2754-vchvln.jpg>, @original_filename="Black-Metal-Gear-Rising-Wallpaper.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"Black-Metal-Gear-Rising-Wallpaper.jpg\"\r\nContent-Type: image/jpeg\r\n">

这表明params[:file]. 我不确定这个参数的使用是否有任何问题。

我该如何解决这个问题?


这是我的post.rb模型和attach_uploader.rb(由carrierwave创建)供需要时参考:

post.rb

class Post < ActiveRecord::Base
    mount_uploaders :attaches, AttachUploader
end

attach_uploader.rb

class AttachUploader < CarrierWave::Uploader::Base
    storage :file
    def store_dir
        "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
    end
end

并且@post.attaches数据库中的列posts

rails g migration add_attaches_to_posts attaches:json
4

1 回答 1

1

我终于找到了解决我问题的方法。感谢carrierwavedanialfarid令人敬畏的ng-file-upload

我的问题是我无法发送所有选定的文件。我的解决方案是

var upload = function (files) {
    var names = [];
    for (var i = 0; i < files.length; ++i)
        names.push(files[i].name);
    return Upload.upload({
        url: '/api/v1/posts',
        file: files,
        fileFormDataName: names
    });
}

然后在我的轨道上 controller.rb

file_arr = params.values.find_all { |value| value.class == ActionDispatch::Http::UploadedFile }

if @post.save
  unless file_arr.empty?
    file_arr.each { |attach|
      @attach = Attach.new
      @attach.filename = attach
      @attach.attachable = @post
      @attach.save
    }
  end
  render json: @post
end

我创建了一个数组来存储我的所有文件params

我尝试使用带有carrierwavemount_uploaders的列来存储文件数组,但是没有用。所以我创建了一个文件表来存储我的文件attaches

class CreateAttaches < ActiveRecord::Migration
  def change
    create_table :attaches do |t|
      t.string :filename
      t.references :attachable, polymorphic: true
      t.timestamps null: false
    end
  end
end

whereattachable用于存储帖子 id 和类型。(这里我的附件属于我论坛中的某个帖子。)


以下是有关设置的一些详细信息(如果需要)

attach.rb(模型)

class Attach < ActiveRecord::Base
  mount_uploader :filename, AttachUploader
  belongs_to :attachable, :polymorphic => true
end

post.rb(模型)

class Post < ActiveRecord::Base
  has_many :attaches, as: :attachable, dependent: :destroy
end

post_serializer.rb

class PostSerializer < ActiveModel::Serializer
  has_many :attaches
end

attach_serializer.rb

class AttachSerializer < ActiveModel::Serializer
  attributes :url, :name

  def url
    object.filename.url
  end

  def name
    object.filename_identifier
  end
end

然后在html文件中可以有一行代码

<div ng-repeat="attach in post.attaches">
    <img ng-src="{{attach.url}}" type="file" height="180" width="320" accept="image/*"/>
    <a target="_self" ng-show="attach.url" href="{{attach.url}}" download="{{attach.name}}">{{attach.name}}<p></p></a>
</div>

我的默认附件用于图像。

于 2015-08-17T04:43:40.047 回答