Rails - 将 base64 图像发送到 AWS S3 存储桶的控制器

Rails - controller to send base64 image to AWS S3 bucket

有人熟悉从 Rails 应用程序将 base64 编码的图像上传到 AWS S3 存储桶吗?我最近关注 this tutorial 使用 AWS-SDK gem 并且它工作得很好 - 对我来说唯一的问题是这解决了从一个好的老式 rails 表单助手上传的问题,我的上传是通过 AJAX 传递到控制器的 JSON 字符串。具体来说,我需要有关如何设置我的控制器的指导,以便它为 AWS 正确拼凑数据。

教程中的 create 控制器如下所示:

def create
    obj = S3_BUCKET.objects[params[:file].original_filename]

    obj.write(
      file: params[:file],
      acl: :public_read
    )

    @upload = Upload.new(
      url: obj.public_url,
      name: obj.key
    )

   if @upload.save
     redirect_to uploads_path, success: 'File successfully uploaded'
   else
     flash.now[:notice] = 'There was an error'
     render :new
   end
end

但我的需要看起来更像下面的控制器,其中编码图像是 JSON 字符串的一部分,即 :report 参数

require "base64"
def create

    @incomingReport = ActiveSupport::JSON.decode(params[:report])

     @incomingReport.each do |x|

        hash = ActionController::Parameters.new(x)

        #IMAGE PROCESSED HERE - THIS DOESN'T WORK, BUT IT IS ILLUSTRATIVE OF WHAT I BELIEVE I NEED
        if hash["image"]
            data = Base64.decode64(hash["image"])
            obj = S3_BUCKET.objects[data]
            obj.write(
               file: data,
               acl: :public_read
            )
            @url = obj.public_url
        end

        @new_report = Report.new(report_params(hash))
        @new_report.image_url = @url
        @new_report.save
    end

    redirect_to root_path
end

所以上面的控制器基本上就是我想要完成的 - 运行 代码生成了一个指向 obj.write( 的 'string contains null byte' 错误,尽管(我并不是真的期待它工作 - 我确定它也有其他问题......比如获取原始文件名......)。对此的任何指导将不胜感激。

为了确保我的数据看起来正确,以下是 image key/value 在 :report 参数中的显示方式(来自我的控制台):

Parameters: {"report"=>"[{"image\":\"data:image/jpeg;base64,/9j/4AAQSkZJR..."}]"}

我找到了这个有用的指南,它看起来可以解决问题:

http://sebastiandobrincu.com/blog/how-to-upload-images-to-rails-api-using-s3