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

9

我有一个图片文件的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。

2个回答

14

我通过使用某种方法解决了问题

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

你能否请发布更多的代码?我发现它非常有趣! - Em Sta
1
@EmSta - 我已经在这里发布了完整的代码。这段代码被添加到我的控制器函数中。请让我知道您需要什么更多的代码。 - Amal Kumar S
在这个版本中,我该如何处理多个扩展名? - Sebastian Corneliu Vîrlan
我不确定,这是否是您实际需要的。从给定的文件路径中,您可以获取扩展名,例如:/pjt_path/public/test.jpg在文件=Tempfile.new(['test', '.jpg'])部分中使用此扩展名 - Amal Kumar S
File.extname("example.pdf/pjt_path/public/test.pdf") 将会返回文件的扩展名。 - Amal Kumar S
显示剩余2条评论


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接