簡體   English   中英

使用Rails在PaperClip中上傳Base64編碼的字符串

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM