【问题标题】:How to display files uploaded using carrierwave, fog and local storage with rails application?如何使用 rails 应用程序显示使用carrierwave、fog 和本地存储上传的文件?
【发布时间】:2013-07-13 03:46:25
【问题描述】:

我正在使用带有雾的carrierwave 在我的服务器上创建一个简单的图像上传过程。 目标是将图像存储在我的服务器中的此文件夹中:

/opt/myapp/uploads/

我已经使用该参数配置了carrierwave和fog,并且上传效果很好:

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

当我上传一张图片时,我可以看到它存储在相应的文件夹中。但是如何在我的网页中显示它们? 生成的url是

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

所以我的应用程序尝试从我的 rails 应用程序目录中的 opt/ 文件夹中获取图像,但我怎么能告诉它从服务器文件系统中检索它们呢?

【问题讨论】:

    标签: ruby-on-rails carrierwave image-uploading fog


    【解决方案1】:

    好的,这很容易做到:

    首先为对应的url添加一个路由:

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

    使用 serve 方法创建 FilesController :

    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
    

    然后我需要在我的 development.rb 和 production.rb 配置文件中添加这一行:

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

    【讨论】:

      猜你喜欢
      • 2016-06-29
      • 2012-07-08
      • 2013-10-09
      • 2018-06-13
      • 1970-01-01
      • 2011-10-07
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多