File upload Base64 encoded string in PaperClip using Rails

10,903

Solution 1

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

Solution 2

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

Share:
10,903
Amal Kumar S
Author by

Amal Kumar S

Ruby on Rails developer #SOreadytohelp

Updated on June 11, 2022

Comments

  • Amal Kumar S
    Amal Kumar S almost 2 years

    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

  • Em Sta
    Em Sta almost 11 years
    can u please post more of your code? I found it very intresting!
  • Amal Kumar S
    Amal Kumar S almost 11 years
    @EmSta - I have posted the complete code here. This code is added in my controller function. Please let me know what more code you needed
  • Em Sta
    Em Sta almost 11 years
    I opend an new question: stackoverflow.com/questions/17336788/… Maybe you can help me @AmalKumarS
  • Amal Kumar S
    Amal Kumar S almost 11 years
    @EmSta - its showing "This question was voluntarily removed by its author."
  • Sebastian Corneliu Vîrlan
    Sebastian Corneliu Vîrlan over 8 years
    on this version how can I handle multiple extention?
  • Amal Kumar S
    Amal Kumar S over 8 years
    I am not sure, is this what you actually need. From the file path given you can get the extention e.g.: /pjt_path/public/test.jpg Use this extension in the file = Tempfile.new(['test', '.jpg']) section
  • Amal Kumar S
    Amal Kumar S over 8 years
    File.extname("example.pdf/pjt_path/public/test.pdf") will return the extension of the file