【问题标题】:ActiveStorage to upload large base64 encoded string?ActiveStorage 上传大型 base64 编码字符串?
【发布时间】:2018-10-12 21:21:20
【问题描述】:

如果我有一张在客户端使用 JavaScript 编辑/生成的图像(例如,裁剪的照片或画布绘制的结果),是否可以使用 ActiveStorage 上传它?

它通常是一个包含"<img src='data:image/jpeg;base64,...=='>" 的大字符串,存储在 JavaScript 变量中,而不是文件中。

【问题讨论】:

    标签: ruby-on-rails rails-activestorage


    【解决方案1】:

    你可以这样做:

    decoded_data = Base64.decode64(params[:base64].split(',')[1])
    resource.image = { 
      io: StringIO.new(decoded_data),
      content_type: 'image/jpeg',
      filename: 'image.jpg'
    }
    

    【讨论】:

      【解决方案2】:

      这有一个宝石。

      看看https://github.com/rootstrap/active-storage-base64

      安装 gem 后非常简单。

      class User < ActiveRecord::Base
        include ActiveStorageSupport::SupportForBase64
      end
      
      
      class User < ApplicationRecord
        has_one_base64_attached :avatar
      end
      

      分配给模型的实例由以下人员完成:

      base64 = 'data:image/png;base64,[base64 data]'
      user.avatar = {data: base64}
      

      【讨论】:

        【解决方案3】:

        据我所知,Active Storage 目前没有对此的原生支持。

        也许this Rails issue 有更多对您有帮助的信息。

        我们已经使用 Shrine(及其 DataURI Plugin)实现了数据 URI 上传,并正在等待有合适的方法使用 Active Storage 执行此操作,然后再进行迁移。

        【讨论】:

          【解决方案4】:

          除了Diego Carrionanswer

          我确实喜欢这个。

          class Booking < ApplicationRecord
            ...
            has_one_attached :signature
            ...
          
          
          
          module Api
            module V1
              class BookingsController < Api::V1::ApiController
              ...
              
                def confirm_hire_details
                  booking = current_user.bookings.find(params[:id])
          
                  if booking.update(booking_params.merge(
                    {
                      signature: signature_decoded
                    }
                  ))
                    ...
                  else
                    ...
                  end
                end
          
                private
          
                def signature_decoded
                  decoded_data = Base64.decode64(params[:signature].split(',')[1])
                  {
                    io:           StringIO.new(decoded_data),
                    content_type: 'image/jpeg',
                    filename:     "signature-#{Time.current.to_i}.jpg"
                  }
                end
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-08-03
            • 2010-11-25
            • 1970-01-01
            • 1970-01-01
            • 2011-04-22
            • 2018-12-28
            • 1970-01-01
            相关资源
            最近更新 更多