8

画像ファイルのbase64でエンコードされた文字列があります。ペーパー クリップを使用して保存する必要があります

私のコントローラーコードは

 @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 を使用してイメージに正しく名前を付けるにはどうすればよいですか。

私はレール3.2、ルビー1.9.2、ペーパークリップ3.0.3を持っています

4

2 に答える 2

13

を使用して問題を修正しました

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
于 2012-05-14T14:34:07.307 に答える
2

:path/:urlオプションを設定してhas_attached_file、拡張子を明示的にオーバーライドしてみてください。

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

それぞれ

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

于 2012-05-10T13:19:43.573 に答える