使用Rails在PaperClip中上传Base64编码的字符串

Ama*_*r S 8 ruby file-upload ruby-on-rails paperclip stringio

我有一个base64编码的图像文件的字符串.我需要使用Paper Clip保存它

我的控制器代码是

 @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
Run Code Online (Sandbox Code Playgroud)

在我的用户模型中

 has_attached_file :profile_pic, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => '/icon.jpg'
Run Code Online (Sandbox Code Playgroud)

目前,该文件保存为文本文件(stringio.txt).但是当我将扩展名更改为JPG时,我可以将其视为图像.如何使用StringIO正确命名图像.

我有rails 3.2,ruby 1.9.2,paperclip 3.0.3

Ama*_*r S 11

我通过使用修复了这个问题

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
Run Code Online (Sandbox Code Playgroud)