In this tip I am going to explain how to upload image to a dropbox account. For uploading image to dropbox we have a Ruby gem “paperclip-dropbox”.
But before uploading image we have to create a dropbox application at https://www.dropbox.com/developers/apps
You have to fill up a form to create an application , below is a sample data for the form
App Type : Core API
App Name: ImageUploader Description:
Sample application for image uploading
Access: Full Dropbox
After submitting the form you will get App Key and App secret.
Now add the paperclip-dropbox gem to gemfile and bundle it.
After bundling authorize your app with any dropbox account to get user_id , access_token , and access_token_secret.
Now run the command
rake dropbox:authorize APP_KEY=your_app_key APP_SECRET=your_app_secret ACCESS_TYPE=your_access_type
It will generate an URL for authorization that you must visit to grant the app access.
After granting the access press enter in console and it will display the your account details(user_id, access_token and access_token_secret) . Then create a dropbox_config.yml file inside config folder of the rails app and add the following details.
app_key: YOUR_APP_KEY
app_secret: YOUR_APP_SECRET
access_token: YOUR_ACCESS_TOKEN
access_token_secret: YOUR_ACCESS_TOKEN_SECRET
user_id: YOUR_USER_ID
Now add the code to your image uploader model , in my case my model name is Image.
Code
class Image < ActiveRecord::Base attr_accessible :picture, :verified, :category, :tags, :user_id #added for paperclip-drop gem has_attached_file :picture, :storage => :dropbox, :dropbox_credentials => "#{Rails.root}/config/dropbox_c onfig.yml", :styles => { :medium => "300x300" , :thumb => "100x100>"}, :dropbox_options => { :path => proc { |style| "#{style}/#{id}_#{picture.original_filename}"}, :unique_filename => true } validates :picture, :attachment_presence => true validates :tags, :presence =>true v validates :category, :presence => true belongs_to :user end
Create a form for image uploading.
{ :class => 'form-horizontal' } do |f| %> 'control-label' %> Select image Change 'file_field' %> Remove 'control-label' %> 'check_box' %> 'control-label' %> 'select_field' %> 'control-label' %> 'text_field' %> 'btn btn-primary' %> t("helpers.links.cancel")), images_path, :class => 'btn' %>
Now save the image in controller and code for it is below
@image = Image.new(params[:image]) respond_to do |format| if @image.save format.html { redirect_to @image, notice: 'Image was successfully created.' } else format.html { render action: "new" } end end