Download a Carrierwave upload from S3

2019-03-31 00:00发布

问题:

I'd like to download an image that was uploaded to S3 using carrierwave. The image is on the Card model, mounted as an uploader. I saw this answer, but had trouble getting that solution to work. My code is:

#download image from S3
uploader = card.image       #image is the mounted uploader
uploader.retrieve_from_store!(File.basename(card.image.url))
uploader.cache_stored_file!

that last line throws: "... caused an exception (undefined method `body' for nil:NilClass)..."

My carrierwave config looks like:

#config/initializers/carrierwave.rb
CarrierWave.configure do |config|
  config.storage = :fog
  config.cache_dir = "#{Rails.root}/tmp/upload"
  ...
end

回答1:

Thanks apneadiving. It was as easy as:

image = MiniMagick::Image::open(card.image.to_s)
image.write(somepath)


回答2:

I have tried this in Rails 5 to download file from AWS S3.

def download
  image = card.image

  # validate existing image from AWS S3
  if image.try(:file).exists?
    data = open(image.url)
    send_data data.read, type: data.content_type, x_sendfile: true
  end

end

I hope help everyone.