CarrierWave不会将文件上传到s3,而是要进行缓存(Heroku上的Sinatra应用)

时间:2018-07-24 19:27:58

标签: ruby heroku amazon-s3 sinatra carrierwave

我有一个Sinatra应用程序,该应用程序可以接收图像并将其上传到s3。我收到的回复说该模型已成功保存,但是在保存时返回的图像URL是缓存的上载。 s3存储桶中也没有图像。下面的代码,是否有明显的错误?我正在关注Railscast #383一集中上传到s3的情况。

感谢您的帮助,我已经尝试了很多方法,但无济于事。

app.rb

    before do
        #Configure Carrierwave
        CarrierWave.configure do |config|
            config.storage = :fog

            config.fog_credentials = {
                provider: "AWS",
                aws_access_key_id: ENV['s3_access_key_id'],
                aws_secret_access_key: ENV['s3_secret_access_key']
            }

            config.fog_directory = ENV['s3_bucket']
            config.fog_public = true
        end
    end

    post "/nominations" do
        image = params[:file] || nil

        nomination = Nomination.create({
            image: image
        })

        if nomination.valid?
            nomination.save

            status 201
            body nomination.image.url
        else
            status 500
            body nomination.errors.messages.to_s.to_json
        end
    end
end

image_uploader.rb

require "carrierwave"
require 'carrierwave/storage/fog'

class ImageUploader < CarrierWave::Uploader::Base

  storage :fog

  def extension_white_list
    %w(jpg jpeg gif png)
  end
end

nomination.rb

class Nomination < ActiveRecord::Base
    extend CarrierWave::Mount

    attr_accessor :image

    mount_uploader :image, ImageUploader
end

1 个答案:

答案 0 :(得分:0)

我直接通过s3上传了

image = params[:file] || ''

uri = URI::Data.new(image)

filename = nom.id.to_s + "_" + Time.now.strftime('%Y%b%d_%H:%M:%S') + '.png'
s3 = Aws::S3::Client.new(
  access_key_id: ENV.fetch('s3_access_key_id'),
  secret_access_key: ENV.fetch('s3_secret_access_key'),
  region: ENV.fetch('s3_region'),
)
response = s3.put_object(bucket: ENV.fetch('s3_bucket'), key: filename, body: uri.data, acl: "public-read")

image = "https://s3.amazonaws.com/" + ENV.fetch('s3_bucket') + "/" + filename