使用 ng-file-upload 和 Rails Carrierwave gem 上传多个文件

2024-04-10

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

客户端 (参考 https://github.com/danialfarid/ng-file-upload#-usage)

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) prints 数组[文件,文件,...](浏览器:FireFox)。所以在客户端它确实获取了选定的文件。上GitHub页的ng-文件上传说它支持文件数组html5.

服务器端 (参考 https://github.com/carrierwaveuploader/carrierwave#multiple-file-uploads)

posts_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]由客户端发送file参数输入Upload.upload.

我想将文件数组存储到@post.attaches, but params[:file]仅包含所选文件中的一个文件。puts params[:file] prints:

#<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(由...制作载波)供需要时参考:

post.rb

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

附加上传器.rb

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

and @post.attaches数据库中的列posts添加者为

rails g migration add_attaches_to_posts attaches:json

我终于找到了解决我的问题的方法。感谢载波 https://github.com/carrierwaveuploader/carrierwave and 丹尼尔法里德 https://github.com/danialfarid太棒了ng-文件上传 https://github.com/danialfarid/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
    });
}

然后在我的rails 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.

我尝试使用一个列mount_uploaders of 载波存储文件数组,但它不起作用。所以我创建一个名为的文件表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

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


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

attach.rb (model)

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

post.rb (model)

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

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

我的默认附件用于图像。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 ng-file-upload 和 Rails Carrierwave gem 上传多个文件 的相关文章

随机推荐