`
a420144030
  • 浏览: 81762 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

图片上传插件 Paperclip

阅读更多

官网:http://thewebfellas.com/blog/2008/11/2/goodbye-attachment_fu-hello-paperclip

 

以前大家可能一直在用attachment_fu上传文件,现在有一个非常方便上传图片的插件Paperclip, 该插件和ImageRmagick结合使用可以设定图片大小等多种功能,同时使用起来也非常方便。下面是具体的使用步骤:

  1. 安装插件

     

ruby script/plugin install git://github.com/thoughtbot/paperclip.git

 

   你也可以在GitHub 下载到该插件

 

     2.   下载ImageMagick

          ImageMagick :  http://www.imagemagick.org/script/binary-releases.php#windows

          Rmagick.gem :  http://rubyforge.org/frs/?group_id=12&release_id=26026

     3.  

Discarding an uploaded image

When an image file is uploaded Paperclip stores it using the original style name. While it isn’t possible to tell Paperclip to simply discard the original image, it is possible to define your own original style which Paperclip will then use. As an example, if your model contains the following:

has_attached_file :photo, 
                  :styles => { :original => '250x250>', 
                               :small => '50x50' }

 

Then even if a huge photo (say 1600x1600) is uploaded, it won’t be stored on your server (or S3 bucket). You will however still have an original file but it will have been resized to 250x250, helping to reduce the amount of storage space needed for attachments.

 

Styles can be Procs too

Most of the time you’ll probably be passing geometry strings for the has_attached_file :styles option, but a very nice feature is the ability to also pass a Proc to provide dynamic geometry string generation. For example, you might have a model that has photo_width and photo_height attributes that can be specified by the user and you want to generate a ‘custom’ thumbnail that uses these dimensions. Paperclip allows you to do this easily:

has_attached_file :photo, 
                  :styles => { :original => '250x250>', 
                               :small => '50x50', 
                               :custom => Proc.new { |instance| "#{instance.photo_width}x#{instance.photo_height}>" } }

 

As you can see the Proc receives the object that the attachment is part of as a parameter and returns a geometry string generated using the photo_width and photo_height attributes. Adding a call to the reprocess! method of the attachment object in your model’s before_save callback also allows you to regenerate the thumbnails if either of these attributes are updated.

Rename files on upload

The has_attached_file :url and :path options can be used to customise the name of your attachments: :url defines the URL that will be used by things like image_tag to access your image and allows you to either provide direct access to the image or to route access through a controller (to provide permission checking for example) and :path determines where the image file is stored either on your server (for file system storage) or in an S3 bucket.

Both options use interpolation, allowing you to use special tags that will be replaced with actual values at runtime (just like regular Ruby string interpolation). The default interpolations provided by the plugin are:

:rails_root
The path to the Rails application.
:rails_env
The current environment (e.g. development, production)
:class
The class name of the model that the attachment is part of, underscored and pluralised for your convenience.
:basename
The name of the originally uploaded file without its extension.
:extension
The file extension of the originally uploaded file.
:id
The ID of the model that the attachment is part of.
:id_partition
The same as :id but formatted as a string using ID partitioning.
:attachment
The name of the attachment attribute (defined in the call to has_attached_file) downcased and pluralised for your enjoyment.
:style
The current style of the attachment file being processed (e.g. in the ‘discarding an uploaded image‘ example above the :style would be one of ‘original’ or ‘small’)

The default :url and :path options for has_attached_file are:

 

:url => "/:attachment/:id/:style/:basename.:extension"
:path => ":rails_root/public/:attachment/:id/:style/:basename.:extension"

 

Let’s say you’d prefer your users’ photos to be stored in a single ‘photos’ subdirectory of the public/images folder on your server using the user ID and style as the base file name. Your model would need to contain something like this:

has_attached_file :photo,
                  :url => "/images/:attachment/:id_:style.:extension",
                  :path => ":rails_root/public/images/:attachment/:id_:style.:extension"

 

If you want to hide images behind a controller do something like this:

has_attached_file :photo,
                  :url => "/:class/:id/:attachment/:style.:extension",
                  :path => ":rails_root/attachments/:class/:id/:attachment/:style.:extension"

 In this example the URL points to a PhotosController nested within the User resource (an example URL would be /users/2/photos/small.png) and the attachment files are stored outside of the public root in a subdirectory of an attachments folder (e.g. RAILS_ROOT/attachments/users/2/photos/small.png). The show action of the PhotosController would be responsible for returning the binary data of the appropriate file using the :style, :extension and :user_id parameters.

Custom interpolations

In addition to the predefined interpolations described above, Paperclip makes it very easy to define your own. For example one of my models has a symbol attribute that I want to use in the file name of images attached to it, so in a Rails initializer I add the following code:

Paperclip::Attachment.interpolations[:symbol] = proc do |attachment, style|
  attachment.instance.symbol.downcase
end

 

Interpolations are Procs that take two parameters, the attachment object and the current style, and it is possible to access the model that the attachment is part of using the instance attribute of the attachment object.

After adding my custom interpolation I can then use it like this:

has_attached_file :logo,
                  :url => '/:attachment/:symbol/:style/:basename.:extension',
                  :path => ':rails_root/public/:attachment/:symbol/:style/:basename.:extension '

 

Deleting an existing attachment

Deleting an existing attachment from a model is as simple as setting the attachment attribute to nil. In a RESTful world you could do this from the destroy action of a controller that maps to the attachment (for example using a DELETE request on /users/1/photos).

You can also quite easily replace an existing attachment by POSTing a new file to your update action. Things get a little trickier if you want to be able to delete an existing attachment without replacing it using an update action.

The approach I’ve used is to add a checkbox to the edit form that when checked causes any existing attachment to be removed unless a new file has also been selected in the file upload box. Here’s the view code:

<% form_for(user, :html => { :multipart => true }) do |f| %>
  <%# lots of exciting form fields %>
  <div>
    <%= f.label(:photo, 'Upload photo') %>
    <%= f.file_field(:photo) %>
  </div>
  <%- unless user.new_record? || !user.photo? -%>
    <div>
      <%= f.label(:delete_photo, 'Delete photo') %>
      <%= image_tag(user.photo.url, :alt => 'Photo', :title => 'Current photo') %>
      <%= f.check_box(:delete_photo) %>
    </div>
  <%- end -%>
  <%# lots more exciting form fields %>
<% end %>

 

This adds a checkbox, using an instance variable to track its value, if the user isn’t new and already has a photo. The instance variable is added to the model like this:

 def delete_photo=(value)
    @delete_photo = !value.to_i.zero?
  end
  
  def delete_photo
    !!@delete_photo
  end
  alias_method :delete_photo?, :delete_photo

 

before_validation :clear_photo

# Later in the model
def clear_photo
  self.photo = nil if delete_photo? && !photo.dirty?
end

 

def update
  if @user.update_attributes(params[:user])
    flash_and_redirect_to('User profile was saved successfully.', :notice, users_path(@user))
  else
    page_title.unshift('Edit user')
    render(:action => 'edit')
  end
end

 

When I was trawling the interwebs to see if anybody else had some code to do this I didn’t find anything, so please let me know if you’ve come up with a better idea but haven’t yet had chance to share it with the world!

Getting clever with validations

I’ve added this section thanks to DMitry’s comment.

Paperclip allows you to validate the presence, content type and size of an attachment file using the validates_attachment_presence, validates_attachment_content_type and validates_attachment_size methods.

But what if you want to do something more advanced? For example let’s say we have a Track model that represents uploaded MP3 files and, because we want to preserve the musical integrity of our site, we want to prevent files from certain ‘artists’ being uploaded. To do this we can use a custom validation method:

class Track < ActiveRecord::Base

  has_attached_file :mp3

  validates_attachment_presence :mp3
  validates_attachment_content_type :mp3, :content_type => [ 'application/mp3', 'application/x-mp3', 'audio/mpeg', 'audio/mp3' ]
  validates_attachment_size :mp3, :less_than => 10.megabytes

  validate :must_have_valid_artist_tag

  protected

    def must_have_valid_artist_tag
      Mp3Info.open(mp3.to_file.path) do |mp3info|
        errors.add(:mp3, 'must not be a Michael Bolton song (what are you thinking?!)') if mp3info.tag.artist == 'Michael Bolton'
      end if mp3?
    rescue Mp3InfoError => e
      errors.add(:mp3, "unable to process file (#{e.message})")
    end

end

 

This model makes use of the gem to access the ID3 tags: you’ll need to install it and set up the necessary config.gem line in your environment.rb file to get this example working.

The first four lines of the model are straight calls to Paperclip methods: they setup the attachment and ensure it is validated for presence, content type and size. The model then contains a validate callback for the must_have_valid_artist_tag method: this is where the good stuff happens.

Here’s a line-by-line breakdown:

  1. If a new MP3 file has been attached then at the time of validation it won’t have been written to the correct location on the server (or S3 bucket). Fortunately the to_file method means we don’t have to worry about this: it returns a File object that will either refer to an existing attachment file or the new, temporary, uploaded file. The first line of the validation method passes the path name of this file to the Mp3Info class so that it can process it.

  2. In this simple example the validation checks if the artist tag of the MP3 file is set to a particular artist and flags an error as appropriate.

  3. Before doing any of the above it’s a good idea to check that a file was actually attached: Paperclip provides a simple way to do this by calling the mp3? method which returns true if a file has been attached. The name of this method is based on the name of your attachment, so for example if your model contains has_attached_file :photo then the photo? method will be used check for an attached file.

  4. The Mp3Info class will raise an Mp3InfoException if something goes wrong. We need to rescue it in case an invalid MP3 file is uploaded.

  5. To keep this example simple, if an exception occurs an error is added to the mp3 attribute containing the exception message: you could naturally do something more impressive here.

By providing you with direct access to the attachment file using the to_file method, Paperclip enables you to do pretty much anything with the attachment, either in a validation like the one shown above or in a different model callback such as before_save.

分享到:
评论

相关推荐

    rails上传文件_paperclip

    NULL 博文链接:https://mylir.iteye.com/blog/800734

    paperclip模板

    Paperclip - Responsive Professional Theme for Business Projects and Mobile Apps Perfect for business and personal use Built with LESS Looks great on all major browsers, tablets and phones 21 unique ...

    dm-paperclip:Thoughtbot的Paperclip插件的DataMapper端口

    DM-Paperclip是Thoughtbot的Paperclip插件的端口,可与DataMapper一起使用。 该插件与原始的面向ActiveRecord的回形针完全兼容。 您可以采用现有的ActiveRecord数据库并将其与DataMapper一起使用。 该模块还包括...

    paperclip-optimizer:缩小回形针图像上传

    可以在以下位置找到Paperclip以及PaperclipOptimizer的保养好的货叉: PaperclipOptimizer是一个处理器,用于优化和缩小上传的图像。 这仅仅是围绕一个瘦包装 ,它支持许多外部优化库如 , , , , , , , , ,...

    paperclip_torrent:生成一个.torrent文件以补充您的回形针上传

    gem 'paperclip_torrent', github: "fattymiller/paperclip_torrent" 在模型中,正常设置has_attached_files ,包括:torrentify处理器,如下所示: has_attached_file :attachment, { styles: { audio_128kbps_...

    Rails的文件附件扩展Paperclip.zip

    Paperclip 是 Rails 框架的一个插件,用于扩展 ActiveRecord 以支持简单的文件附件的功能。 标签:Paperclip

    administrate-field-paperclip:用于管理的回形针字段插件

    一个在集成字段的插件。 ,因此从0.0.6版开始,此宝石依赖于 paperclip,这是一个持续进行中的分支。 如果您仍在使用不推荐使用的Paperclip版本,则0.0.5版仍然适合您。 指示 将administrate-field-paperclip ...

    phrails-paperclip:一个插件,将上传文件并检索它们以供显示

    ImageMagick - http://www.php.net/manual/en/book.imagick.phpPhrails-Paperclip Ini 文件该插件需要 Phrails 项目中的 config/phrails-paperclip.ini。 It can be empty for use with File type attachments.我们...

    paperclip-av-transcoder, 使用 ffmpeg/avconv的Paperclip 音频/视频转码器.zip

    paperclip-av-transcoder, 使用 ffmpeg/avconv的Paperclip 音频/视频转码器 Paperclip 转码器使用 ffmpeg/avconv的Paperclip 音频/视频转码器。这是( https://github.com/owahab/paperclip-ffmpeg )的替代品。状态

    paperclip-s3-tutorial-korean:回形针文件上传到 s3 韩文

    回形针上传到 S3 要求 aws-sdk 回形针 宝石安装 Gemfile gem ' aws-sdk ' gem ' paperclip ' 并运行 bundle install 创建 s3 这里 设置s3信息 从获取访问密钥和秘密密钥并将它们写好。 然后创建一个config/aws....

    paperclip

    回形针 回形针旨在用作ActiveRecord的简单文件附件库。 其目的是使设置尽可能简单,并尽可能将文件与其他属性一样对待。 这意味着它们不会保存到磁盘上的... Paperclip现在需要Ruby版本&gt; = 2.0.0和Rails版本3.2,&gt; =

    paperclip-example:在 Rails 4.0.0 中使用 Paperclip 和 S3 的示例

    在 Rails 4.0.0 上运行带有 AWS S3 演示的 Paperclip 教程这是一个教程和演示,用于获取在 Rails 4.0.0 上运行的带有 AWS S3 上传的 Paperclip。 在本教程中,我们将创建一个简单的站点,可以在其中创建文章并可以将...

    paperclip_watermark:回形针处理器在图像上应用水印

    回形针水印描述这是一个简单的 Paperclip 处理器,用于在 Paperclip 的图像上应用水印。 水印将调整大小以适合基本图像。 很少有选项可用于指定位置和不透明度: watermark_distance_from_top : 以百分比指定从顶部...

    paperclip-s3:未维护

    每一个当您将应用程序部署到,您正在更改RAILS_ROOT,因此您所有上传的文件都将丢失,您的存储桶将一团糟! 默认的Heroku工作路径是默认路径。 如何使用 使用以下命令将宝石添加到您的Gemfile中 gem “paperclip-...

    1.12.2paperclip.jar

    大家对服务端应该都不陌生了,我就不多介绍了,主要是点击server.jre,需要用JAVA8 64位运行,然后稍等一会,会生成mod文件夹,运行配置同意elua协议就可以开服务器了

    1.16.5-paperclip.jar

    免责声明:资料部分来源于合法的互联网渠道收集和整理,部分自己学习积累成果,供大家学习参考与交流。收取的费用仅用于收集和整理资料耗费时间的酬劳。 本人尊重原创作者或出版方,资料版权归原作者或出版方所有,...

    paperclipfans:Hi〜这里是回形针PaperClip非官方的资料整理仓库,我们迫切的希望您的帮助整理,这将加速我们的网站维护每一期的文字稿及图片内容

    氦,这里是回形针PaperClip内容收录仓库,你可以在这里找到往期节目的相关内容。 使用 在线浏览 目前,我们有以下站点供您在线浏览本仓库的内容。 GitHub页面 该站点由GitHub Actions自动构建并部署在GitHub Pages...

    mongoid-paperclip:蒙古族

    设定宝石文件gem "mongoid-paperclip" 接下来,假设我们有一个用户模型,并且我们希望允许我们的用户上传头像。 Rails.root / app / models / user.rb-包含Mongoid :: Paperclip模块并调用提供的类方法class User ...

    node-paperclip-ffmpeg

    这是一个可与node-paperclip一起使用的插件。 它允许您传递任何要ffmpeg的选项,然后流式传输到文件系统或云。 安装 sudo add-apt-repository ppa:djcj/hybrid sudo apt-get update sudo apt-get install ffmpeg #...

    :paperclip:ZSH插件,可提醒您对刚刚键入的命令使用现有别名-Linux开发

    您应该使用简单的zsh插件,该插件提醒您应该对刚刚键入的命令使用现有别名之一。 还支持检测全局别名和git别名。 使用需求安装您应该使用简单的zsh插件,该插件提醒您应该对刚刚键入的命令使用现有别名之一。 还支持...

Global site tag (gtag.js) - Google Analytics