纸夹文件上传

我有一个场景,在同一个表单中,我有两个上传,一个是图像类型,而另一个是doc,excel和PDF等。我正在使用gem’paper-clip’。 首先我想知道如何自定义和配置回形针以上传两种类型,其次我想限制两个字段不上传其他类型。 像图像字段不应该接受其他内容类型,反之亦然。

你可以查一下

Paperclip上传文件: – 1)在Gemfile中包含Gemfile中的gem:

gem "paperclip", "~> 3.0" 

如果你仍在使用Rails 2.3.x,你应该这样做:

  gem "paperclip", "~> 2.7" 

2)在你的模型中

 class User < ActiveRecord::Base attr_accessible :img_avatar, :file_avatar has_attached_file :img_avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png" has_attached_file :file_avatar, :default_url => "/files/:style/missing.doc" end 

3)在您的迁移中:

  class AddAvatarColumnsToUsers < ActiveRecord::Migration def self.up add_attachment :users, :img_avatar add_attachment :users, :file_avatar end def self.down remove_attachment :users, :img_avatar remove_attachment :users, :file_avatar end end 

在您的编辑和新视图中:

  <%= form_for @user, :url => users_path, :html => { :multipart => true } do |form| %> <%= form.file_field :img_avatar %> <%= form.file_field :file_avatar %> <% end %> 

在你的控制器中:

 def create @user = User.create( params[:user] ) if ["jpg,"jpeg","gif", "png"].include? File.extname(params[:img_avatar]) @user.img_avatar = params[:img_avatar] elsif ["doc","docx","pdf","xls","xlsx"].include?File.extname(params[:file_avatar]) @user.file_avatar = params[:file_avatar] else flash[:message] = "You are uploading wrong file" #render flash message end 

结束

谢谢

扩展所选答案(并修复你的ArgumentError)..

您可以将所有内容validation放在has_attached_file下的模型中,如下所示:

 validates_attachment_content_type :img_avatar, :content_type => /^image\/(png|jpeg)/ validates_attachment_content_type :file_avatar, :content_type =>['application/pdf'] 

这将允许img_avatar的附件类型只有png和jpeg(你可以添加其他扩展名)和file_avatar,在这种情况下,只有pdf-only 🙂