Paperclip upload image via console

It is very easy to associate an image with a model using ruby console, given you are associating image to the model using paperclip.
Here is what you are gonna do

url="http://golygon.com/image_url.png"
file = open url //Ruby will fetch the image using HTTP on your server
@user.photo = file // User model uses paperclip to associate photo. This will do the trick
@user.save

Don’t want to use multipart at client side and still want to associate image to the the model using paperclip? You can do a simple binary upload from the client and handle it at server using following commands

uploaded_io = params[:photo][:data] //read data in binary format uploaded by client/browser
name=params[:photo][:filename] || "uploads.jpg" //file-name
base_dir = Rails.root.join('public', 'system', 'photos' ) //Make sure you have the right target directory
new_dir = File.join(base_dir, @user.id.to_s)
if !File.directory?(new_dir)
  Dir.mkdir(new_dir, 0700)
end

File.open(File.join(new_dir, name), 'w:ASCII-8BIT') do |file|
  file.write(Base64.decode64(uploaded_io)) //saves file at some temp location on your server
  file.close
end

Now that you have file on your server, you can run the first code snippet to read it from the location you just saved the file and associate it with the parent model using paperclip internally.

Comments