file uploading through paperclip in rails 3.x
DESCRIPTION
Paperclip is an easy file attachment library for Rails applications. Attached files are saved to the file system, database or cloud and referenced in the browser by an easily understandable specification.TRANSCRIPT
File uploading through Paperclip in rails 3.x
Paperclip is an easy file attachment library for Rails applications. Attached files are saved to the
file system, database or cloud and referenced in the browser by an easily understandable
specification.
Here is an example to explain the image attachment for a user profile in an application. This
example narrates about saving the image in the file system. However, the images can be saved in
S3 bucket [Amazon Simple Storage Service, S3] or database.
Step#1
ImageMagick must be installed in the system and Paperclip must have access to it. ImageMagick is
a software suite to create, edit, compose, or convert bitmap images. It can read and write images
in a variety of formats. You can download it by visiting the following URL:
http://www.imagemagick.org/script/index.php
Step#2
Include the paperclip gem in your Gemfile
gem "paperclip"
Then run the bundler to install the gem
bundle install
Step#3
Add the fields for the image processing as below in your migration file
class CreateUsers < ActiveRecord::Migration
def change create_table :users do |t| t.string :name
t.string :photo_file_name t.string :photo_content_type t.string :photo_file_size
t.timestamps end endend
Then run your migration files
rake db:migrate
Step#4
Modify the user model for cropping and save image in your system folder
has_attached_file :photo, :styles => { :small => "150x150>" }, :url => "/system/:attachment/:id/:style/:basename.:extension", :path => ":rails_root/public/system/:attachment/:id/:style/:basename.:extension"
Here you can specify the file path and the image size as per the requirement.
Step#5
Modify your view file to upload an image
<%= form_for :user,:url => {:action => "create"}, :html => { :multipart => true } do |f| %> <%= f.file_field :photo %> <% end %>
Step#6
Write the following code to display the image of a user
<%= image_tag @user.photo.url (:small)%>