简体   繁体   English

S3上的Carrierwave上传和访问文件

[英]Carrierwave upload and access file on S3

I am struggling to access files on S3 with Carrierwave. 我正在努力使用Carrierwave访问S3上的文件。

In my uploader file doc_uploader.rb I have the following code 在我的上传器文件doc_uploader.rb中,我有以下代码

storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end

to uplooad "doc" model defined as follow 上传“doc”模型定义如下

class Doc < ActiveRecord::Base
belongs_to :user
mount_uploader :doc, DocUploader
end

To access the uploaded file I have the following line of code in a controller 要访问上传的文件,我在控制器中有以下代码行

@doc = current_user.docs.order("created_at").last #last file uploaded by user
io = open("#{Rails.root}/public" + @doc.doc.url)

Everything works perfectly locally. 一切都在当地完美运作。 Now I want to move my file to S3 in the uploader I use fog and replace 现在我想在上传器中将我的文件移动到S3,我使用雾并替换

storage :file

by 通过

storage :fog

I adjust my config file carrierwave.rb and uploading works perfectly . 我调整配置文件carrierwave.rb并完美上传 However, to access the file I try to use 但是,要访问我尝试使用的文件

@doc = current_user.docs.order("created_at").last
io = open("#{@doc.doc.url}")

and I get the following error 我收到以下错误

No such file or directory @ rb_sysopen - /uploads/doc/doc/11/the_uploaded_file.pdf

Could anyone give me the right syntax to access the file on S3 please? 有人能给我正确的语法来访问S3上的文件吗? Thanks. 谢谢。

When accessing the asset through the console, it gives you only the path, you might need to append the protocol & host to the @doc.doc.url , something like: 通过控制台访问资产时,它只提供路径,您可能需要将协议和主机附加到@doc.doc.url ,例如:

io = open("http://example.com#{@doc.doc.url}")

Or you can set the asset url on the environment you need to, but this is not really necessary: 或者您可以在您需要的环境中设置资产网址,但这不是必需的:

 config.asset_host = 'http://example.com'

This only applies if you are using the console, on any web view this will not apply, carrierwave seems to handle it 这仅适用于您使用控制台的情况,在任何不适用的Web视图上,carrierwave似乎都在处理它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM