简体   繁体   English

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

[英]File upload Base64 encoded string in PaperClip using Rails

I have at base64 encoded string of a image file. 我有一个base64编码的图像文件的字符串。 I need to save it using Paper Clip 我需要使用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). 目前,该文件保存为文本文件(stringio.txt)。 But when I change the extension to JPG I can view it as image. 但是当我将扩展名更改为JPG时,我可以将其视为图像。 How can I name the image correctly using StringIO. 如何使用StringIO正确命名图像。

I am having rails 3.2, ruby 1.9.2, paperclip 3.0.3 我有rails 3.2,ruby 1.9.2,paperclip 3.0.3

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

Try setting the :path / :url option of has_attached_file and explicitly overriding the extension: 尝试设置has_attached_file:path / :url选项并显式覆盖扩展名:

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

respectively 分别

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM