【问题标题】:How to upload a Base 64 image to Rails paperclip如何将 Base 64 图像上传到 Rails 回形针
【发布时间】:2014-12-01 17:42:10
【问题描述】:

我已经在互联网上尝试了上百万个不同的教程,了解如何将 Base64 图像从我的 iOS 应用程序上传到我的 rails 应用程序。似乎无论我如何格式化请求,它都不会被接受。

有人确切知道如何将 Base64 图像上传到回形针吗?

我尝试将参数作为 JSON 发送

{ "thumbnail_image": "base64_data..." }

我也尝试附加数据 url

{ "thumbnail_image": "data:image/jpeg;base64,alkwdjlaks..." }

我尝试发送带有和不带有数据 url 的 JSON 对象

{ "thumbnail_image": { "filename": "thumbnail.jpg", "file_data": "base64_data...", "content_type": "image/jpeg" } }

我不断收到这些Paperclip::NoHandlerErrors,然后它会将大量数据转储到我的日志中。

【问题讨论】:

    标签: ruby-on-rails json paperclip


    【解决方案1】:

    您的 Base64 字符串似乎没问题。您可以随时检查 here

    所以问题可能出在 Rails 方面。检查您收到的字符串是否与您发送的字符串完全相同。

    使用 Paperclip 4.2.1 我设法以这种方式保存 Base64 GIF 文件:

    拥有:

    class Thing
        has_attached_file :image
    

    和 POST 属性:

    {
        "thumbnail_data:" "data:image/gif;base64,iVBORw0KGgo..."
    }
    

    您所要做的就是找到合适的适配器并指定 original_filename。所以对于控制器来说:

    def create
        image = Paperclip.io_adapters.for(params[:thumbnail_data]) 
        image.original_filename = "something.gif"
        Thing.create!(image: image)
        ...
    end
    

    AFAIK Paperclip 使从 3.5.0 版本保存 base64 变得更加容易。

    希望对您有所帮助!

    【讨论】:

    • 确实,这至少在 Paperclip 3.5.4 中有效。但是,它在 v. 3.4.2 中不起作用。
    【解决方案2】:

    这就是我过去的做法,它基本上是一种蛮力方法,不确定回形针是否在最近的版本中增加了更好的支持,但这应该可以工作

    class FooBar < ActiveRecord::Base
      has_attached_file :thumbnail_image
      validates_attachment_content_type :thumbnail_image,
                                         content_type: %w(image/jpeg image/jpg image/png image/gif),
                                         message: "is not gif, png, jpg, or jpeg." 
    
      attr_accessor :base64_thumbnail_image
    
      # call this explicitly from the controller or in an after_save callback
      # after setting the base64_thumbnail_image attribute
      def save_base64_thumbnail_image
        if base64_thumbnail_image.present?
          file_path = "tmp/foo_bar_thumbnail_image_#{self.id}.png"
          File.open(file_path, 'wb') { |f| f.write(Base64.decode64(base64_thumbnail_image)) }
          # set the paperclip attribute and let it do its thing
          self.thumbnail_image = File.new(file_path, 'r')
        end
      end  
    end
    
    # params should be base64_thumbnail_image, not thumbnail_image in this case
    

    【讨论】:

    • 这看起来很有希望。很糟糕的是,回形针基本上忽略了已成为最常见的图像提交格式之一:(
    • 不幸的是我收到了这个错误。它实际上并没有引发异常,但是没有保存图像Content Type Spoof: Filename thumbnail18.png (["image/png"]), content type discovered from file command: text/plain. See documentation to allow this combination.
    • @BrianWheeler - 这是一个单独的问题 - 对于您允许的任何图像类型,您需要在模型上添加 validates_attachment_content_type - 我将添加到上面的代码示例中
    • 我认为它比这更深入,因为我有一个适合文件附件验证器的正则表达式
    猜你喜欢
    • 2016-06-16
    • 1970-01-01
    • 2018-08-25
    • 2016-03-31
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多