简体   繁体   English

Ruby on Rails:使用carrierwave上传多个文件

[英]Ruby on Rails: multiple file upload with carrierwave

I've implemented a file upload for my users in my ruby on rails app. 我已经在我的ruby on rails app上为我的用户实现了文件上传。 Each user can upload an xml file, but now I was trying to do it with multiple files, but I'm having some problems. 每个用户都可以上传一个xml文件,但现在我试图用多个文件来做,但是我遇到了一些问题。 Can anyone give me an example on how can I upgrade my code? 任何人都可以举例说明如何升级我的代码?

I already can upload multiple files, and I can see them in the DB, but If I upload more (for example 1) he overwrites the previous files. 我已经可以上传多个文件,我可以在数据库中看到它们,但如果我上传更多(例如1),他会覆盖以前的文件。 And how can I list all user files? 我如何列出所有用户文件?

EDIT: 编辑:

I need to upload only one file at each time (without the multiple: true). 我需要每次只上传一个文件(没有倍数:true)。 My objective is to add more files after the user uploaded one . 我的目标是在用户上传文件后添加更多文件

Documentation excerpt. 文档摘录。

Add a column which can store an array. 添加一个可以存储数组的列。 This could be an array column or a JSON column for example. 例如,这可以是数组列或JSON列。 Your choice depends on what your database supports. 您的选择取决于您的数据库支持的内容。 For example, create a migration like this: 例如,创建一个这样的迁移:

rails g migration add_avatars_to_users avatars:json
rake db:migrate

Open your model file and mount the uploader: 打开模型文件并安装上传器:

class User < ActiveRecord::Base
  mount_uploaders :avatars, AvatarUploader
end

Make sure your file input fields are set up as multiple file fields. 确保将文件输入字段设置为多个文件字段。 For example in Rails you'll want to do something like this: 例如在Rails中你会想要做这样的事情:

<%= form.file_field :avatars, multiple: true %>

Also, make sure your upload controller permits the multiple file upload attribute, pointing to an empty array in a hash. 此外,请确保您的上传控制器允许多文件上载属性,指向散列中的空数组。 For example: 例如:

params.require(:user).permit(:email, :first_name, :last_name, {avatars: []})

Now you can select multiple files in the upload dialog (eg SHIFT+SELECT), and they will automatically be stored when the record is saved. 现在您可以在上传对话框中选择多个文件(例如SHIFT + SELECT),并在保存记录时自动存储它们。

u = User.new(params[:user])
u.save!
u.avatars[0].url # => '/url/to/file.png'
u.avatars[0].current_path # => 'path/to/file.png'
u.avatars[0].identifier # => 'file.png'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM