Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File upload Base64 encoded string in PaperClip using Rails

I have at base64 encoded string of a image file. I need to save it using Paper Clip

My Controller code is

 @driver = User.find(6)
 encoded_file = Base64.encode64(File.open('/pjt_path/public/test.jpg').read)
 decoded_file = Base64.decode64(encoded_file)

 @driver.profile_pic =  StringIO.open(decoded_file)
 @driver.save

In my user model

 has_attached_file :profile_pic, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => '/icon.jpg'

Currently the file is saved as a text file(stringio.txt). But when I change the extension to JPG I can view it as image. How can I name the image correctly using StringIO.

I am having rails 3.2, ruby 1.9.2, paperclip 3.0.3

like image 660
Amal Kumar S Avatar asked May 10 '12 13:05

Amal Kumar S


2 Answers

I fixed the issue by using

encoded_file = Base64.encode64(File.open('/pjt_path/public/test.jpg').read)
decoded_file = Base64.decode64(params[:encoded_image])
begin
  file = Tempfile.new(['test', '.jpg']) 
  file.binmode
  file.write decoded_file
  file.close
  @user.profile_pic =  file
  if @user.save
    render :json => {:message => "Successfully uploaded the profile picture."}
  else
    render :json => {:message => "Failed to upload image"}
  end
ensure
  file.unlink
end
like image 66
Amal Kumar S Avatar answered Sep 28 '22 02:09

Amal Kumar S


Try setting the :path/:url option of has_attached_file and explicitly overriding the extension:

http://rdoc.info/gems/paperclip/Paperclip/ClassMethods#has_attached_file-instance_method

respectively

http://rdoc.info/gems/paperclip/Paperclip/Storage/Filesystem

like image 29
flooooo Avatar answered Sep 28 '22 03:09

flooooo