58

PingFMに画像をアップロードしようとしています。彼らのドキュメントには次のように書かれています。

media – base64 encoded media data.

この画像にはURLからアクセスできます。私はこれを試しました(実際に推測しました):

ActiveSupport::Base64.encode64(open("http://image.com/img.jpg"))

しかし、私はこのエラーを受け取ります:

TypeError: can't convert Tempfile into String
    from /usr/lib/ruby/1.8/base64.rb:97:in `pack'
    from /usr/lib/ruby/1.8/base64.rb:97:in `encode64'
    from (irb):19
    from :0
4

6 に答える 6

87

ファイルをエンコードするには:

require 'base64'
Base64.encode64(File.open("file_path", "rb").read)

エンコードされた文字列からファイルを生成するには:

require 'base64'
encoded_string = Base64.encode64(File.open("file_path", "rb").read)

File.open(file_name_to_create, "wb") do |file|
    file.write(Base64.decode64(encoded_string))
end
于 2011-09-22T06:07:27.047 に答える
52

openメソッド:

open("http://image.com/img.jpg")

文字列を期待している間、Tempfileオブジェクトを返していますencode64

一時ファイルを呼び出すreadと、うまくいくはずです。

ActiveSupport::Base64.encode64(open("http://image.com/img.jpg") { |io| io.read })
于 2009-10-10T10:49:47.927 に答える
23

これも機能します、少しきれいです

 require 'base64'

 Base64.encode64(open("file_path").to_a.join)

「これをどのようにデコードしてファイルに戻しますか?」-@ user94154

 require 'base64'

 open('output_file_name.txt', 'w') do |f| 
   f << Base64.decode64( encoded_content )
 end

encoded_content以前にエンコードされたファイルコンテンツの戻り値はどこになりますか。

于 2010-12-21T16:01:01.977 に答える
11

ファイルをbase64エンコーディングにエンコードします。

File.open("output_file","w"){|file| file.write [open("link_to_file").string].pack("m")}

base64でエンコードされたファイルをデコードします。

File.open('original', 'wb') {|file| file << (IO.readlines('output_file').to_s.unpack('m')).first }
于 2009-10-10T04:42:48.363 に答える
3

これが私の解決策です:

1: このカスタム image_tag メソッドを ApplicationHelper に入れ、ActiveSupport モジュールを含めます

module ApplicationHelper
  include ActiveSupport
  def image_tag_base64(file_path, mime_type = 'image/jpeg', options = {})
    image_tag("data:#{mime_type};base64,#{Base64.encode64(open(file_path) { |io| io.read })}", options)
  end
end

2: 次に、base64 でエンコードされた画像を使用するビュー内で、次のようなメソッドを使用します。

<%= image_tag_base64 @model.paperclip_attribute.path(:size), @model.paperclip_attribute.content_type, {class: 'responsive-img etc etc'} %>

3: 完了

于 2017-08-27T22:30:27.950 に答える