How to encode media in base64 given URL in Ruby

后端 未结 6 1116
野性不改
野性不改 2020-12-04 15:08

I\'m trying to upload an image to PingFM. Their documentation says:

media – base64 encoded media data.

I can access this image via the URL.

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 15:50

    Here's my solution:

    1: Put this custom image_tag method into ApplicationHelper, and include ActiveSupport module

    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: Then, inside the view you want to use base64 encoded image use the method like this:

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

    3: DONE

提交回复
热议问题