【问题标题】:Paper clip files upload回形针文件上传
【发布时间】:2013-07-26 05:04:33
【问题描述】:

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

【问题讨论】:

  • 自定义纸夹见github.com/thoughtbot/paperclip第二:--上传时你可以检查扩展名,比如File.extname,它会给你扩展名,所以如果它是jpg,png,gif,jpeg,那么它会否则上传,它将由第一个上传
  • 我的模型中有这个,但它不起作用.. has_attached_file :document validates_attachment :document, content_type: "application/pdf"
  • ArgumentError(您必须将 :content_type 或 :not 传递给验证器):

标签: ruby-on-rails ruby-on-rails-3 paperclip


【解决方案1】:

你可以检查

回形针上传文件:-- 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 

结束

谢谢

【讨论】:

  • 先告诉我如何上传文件:)
  • Ok 请参阅回形针指南 github.com/thoughtbot/paperclip 上传文件
  • 请参阅我的帖子以了解您的情况两次以不同方式上传
【解决方案2】:

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

您可以将模型中的所有内容验证放在 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 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多