rev*_*ves 11 ruby-on-rails carrierwave
我有一个rails 3.1应用程序,我正在添加carrierwave来存储图像.但我想将这些图像存储在公共文件夹之外,因为只有在用户加载到应用程序中时才能访问这些图像.所以我用初始化文件更改了carrerwave中的store_dir:
CarrierWave.configure do |config|
config.root = Rails.root
end
Run Code Online (Sandbox Code Playgroud)
我的载波上传器是这样的:
class ImageUploader < CarrierWave::Uploader::Base
...
def store_dir
"imagenes_expedientes/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
Run Code Online (Sandbox Code Playgroud)
图像存储正确,如果我使用公用文件夹一切正常.但是,当试图将事物移动到私人文件夹时,图像不会显示,当我尝试在新窗口中打开它时,我收到以下错误:
Routing Error
No route matches [GET] "/imagenes_expedientes/volunteer/avatar/15/avatar.jpg"
Run Code Online (Sandbox Code Playgroud)
我试图通过控制器使用send_file传递文件,但不是加载页面我只得到下载的图像.
def show
send_file "#{Rails.root}/imagenes_expedientes/avatar.jpg", :type=>"application/jpg", :x_sendfile=>true
end
Run Code Online (Sandbox Code Playgroud)
最后,图像在视图中显示如下:
<%= image_tag(@volunteer.avatar_url, :alt => "Avatar", :class => "avatar round") if @volunteer.avatar? %>
Run Code Online (Sandbox Code Playgroud)
这可能很容易解决,但由于我对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
Run Code Online (Sandbox Code Playgroud)
添加到路线:
resources :volunteers do
member do
get 'image'
end
end
Run Code Online (Sandbox Code Playgroud)
并显示在视图中:
<%= image_tag(image_volunteer_path(@volunteer), :alt => "Avatar", :class => "avatar round") if @volunteer.avatar? %>
Run Code Online (Sandbox Code Playgroud)
希望它能帮到别人!
:disposition => 'inline' 将使您的图像显示在浏览器中,而不是弹出下载对话框.
def show
send_file "#{Rails.root}/imagenes_expedientes/avatar.jpg", :disposition => 'inline', :type=>"application/jpg", :x_sendfile=>true
end
Run Code Online (Sandbox Code Playgroud)
根据图像大小和用户数量,您可能希望将此操作移动到金属应用程序,或单独使用以便不阻止服务器.
| 归档时间: |
|
| 查看次数: |
4937 次 |
| 最近记录: |