ruby-on-rails – 使用Rails在PaperClip中上传Base64编码的字符串

我有一个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

在我的用户模型中

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

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

我有rails 3.2,ruby 1.9.2,paperclip 3.0.3

解决方法

我通过使用修复了这个问题
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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...