从S3下载Carrierwave上传文件

5
我想下载使用carrierwave上传到S3的图像。该图像位于Card模型上,作为一个上传器被挂载。我看到了这个答案,但是在尝试那个解决方案时遇到了麻烦。我的代码如下:
#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!

最后一行抛出了异常:"...导致异常(未定义方法 `body' for nil:NilClass)..."

我的carrierwave配置如下:

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

1
你可以这样做:file = open card.image.url - apneadiving
2个回答

3

感谢apneadiving。它就像这样简单:

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

哇,我不知道ImageMagick可以用这种方式下载和保存文件,只需要URL,太棒了! - Rafael Oliveira
你能进一步解释这是如何工作的吗?这段代码应该放在哪里? - Serge Pedroza
我已经将那段代码放在一个自定义的后台作业中,用于从S3下载图像。但它可能出现在任何地方。 - joseph.hainline
@joseph.hainline 我想为用户提供下载选项,但我不知道用户的系统路径在哪里。你在代码中写了 somepath,我该如何指定路径? - Supertracer

2
我尝试在Rails 5中从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

我希望能够帮助大家。

这段内容与IT技术无关。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接