【发布时间】:2011-11-11 05:06:59
【问题描述】:
我有一个 rails 3.1 应用程序,我正在添加carrierwave 来存储图像。但是我想将这些图像存储在公共文件夹之外,因为它们应该只有在用户加载到应用程序时才能访问。所以我用初始化文件改变了carrerwave中的store_dir:
CarrierWave.configure do |config|
config.root = Rails.root
end
我的carrierwave上传器是这样的:
class ImageUploader < CarrierWave::Uploader::Base
...
def store_dir
"imagenes_expedientes/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
图像存储正确,如果我使用公用文件夹,一切正常。但是,当尝试将内容移动到私人文件夹时,不会显示图像,当我尝试在新窗口中打开它们时,会出现以下错误:
Routing Error
No route matches [GET] "/imagenes_expedientes/volunteer/avatar/15/avatar.jpg"
我试图通过控制器使用 send_file 传递文件,但我没有加载页面,而是只下载了图像。
def show
send_file "#{Rails.root}/imagenes_expedientes/avatar.jpg", :type=>"application/jpg", :x_sendfile=>true
end
最终图像在视图中显示如下:
<%= image_tag(@volunteer.avatar_url, :alt => "Avatar", :class => "avatar round") if @volunteer.avatar? %>
这可能很容易解决,但由于我对 Rails 有点陌生,所以我不知道该怎么做。我应该设置路线吗?或者有没有使用 send_file 方法显示图像?
谢谢!
回答
我设法使用 x-sendfile 显示图像,并按照clyfe 的建议放置 :disposition => 'inline'。我在控制器中做了一个新动作:
def image
@volunteer = Volunteer.find(params[:id])
send_file "#{Rails.root}/imagenes_expedientes/#{@volunteer.avatar_url}",:disposition => 'inline', :type=>"application/jpg", :x_sendfile=>true
end
添加到路线:
resources :volunteers do
member do
get 'image'
end
end
并显示在视图中:
<%= image_tag(image_volunteer_path(@volunteer), :alt => "Avatar", :class => "avatar round") if @volunteer.avatar? %>
希望对他人有所帮助!
【问题讨论】:
-
如果我们将它存储在应用程序文件夹之外,那么我们需要做什么?