Search code examples
ruby-on-railscarrierwaveimage-uploadingfog

How to display files uploaded using carrierwave, fog and local storage with rails application?


I am using carrierwave with fog to create a simple image uploading process on my server. The goal is to have images stored in my server in this folder :

/opt/myapp/uploads/

I have configured carrierwave and fog with that parameters and the upload is working very well :

CarrierWave.configure do |config|

  config.fog_credentials = {
    :provider               => 'Local', 
    :local_root             => '/opt/myapp/' 
  }
  config.fog_public     = false               
  config.fog_directory  = 'uploads/' 

  config.storage = :fog
  config.asset_host = proc do |file|
    '/opt/myapp/uploads/'
  end
end

When I upload an image I can see that it is stored in the corresponding folder. But how can I display them in my web pages ? The generated url is

http://localhost:3000/opt/myapp/uploads/<path-to-my-image>.png

So my application tries to get images from an opt/ folder in my rails application directory, but how could I tell it to retrieve them from the server filesystem instead ?


Solution

  • Ok,that was easy to do :

    First add a route for the corresponding urls :

    match '/opt/myapp/uploads/:file_name' => 'files#serve'
    

    The create a FilesController with a serve method :

    class FilesController < ApplicationController
    
      def serve
        before_filter :authenticate_user! #used with Devise to protect the access to the images
        path = "/opt/myapp/uploads/#{params[:file_name]}.png"
    
        send_file( path,
          :disposition => 'inline',
          :type => 'image/png',
          :x_sendfile => true )
      end
    end
    

    Then I needed to add this line in my development.rb and production.rb configuration files :

    config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" #to use with Thin and Nginx