简体   繁体   中英

Carrierwave upload and access file on S3

I am struggling to access files on S3 with Carrierwave.

In my uploader file doc_uploader.rb I have the following code

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

to uplooad "doc" model defined as follow

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

storage :file

by

storage :fog

I adjust my config file carrierwave.rb and uploading works perfectly . 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? 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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