如何从视图内的私人文件夹显示图像?
-
21-12-2019 - |
题
我需要一个看起来很简单的快速提示。我在私人文件夹中有一些图片,并希望在我的视图中显示它们。
我找到的唯一解决方案是这样的:
def show
send_file 'some/image/url', :disposition => 'inline', :type => 'image/jpg', :x_sendfile => true
end
我读过 :disposition => 'inline'
不应该触发图像下载,并允许我在我的视图中显示它。问题是每次我触发 show
动作,图像下载自动激活,它是自动下载。查看 show
操作不显示。
如何在我的视图中显示该图像?谢谢!.
解决方案
我这样做的方式,我并不是说这本书是完美的,是我为图像做了一个根,并在控制器中做了一个动作来渲染它。
例如,在路由中。rb
match '/images/:image', to: "your_controller#showpic", via: "get", as: :renderpic
在您的控制器中:
def showpic
send_file "some/path/#{params[:image]}.jpg", :disposition => 'inline',
:type => 'image/jpg', :x_sendfile => true # .jpg will pass as format
end
def show
end
在你看来
<img src="<%= renderpic_path(your image) %>">
这是一个工作示例,"send_file"上的参数较少
def showpic
photopath = "images/users/#{params[:image]}.jpg"
send_file "#{photopath}", :disposition => 'inline'
end
其他提示
我想问题是 type
.从文档:
:type - specifies an HTTP content type
所以正确的HTTP内容类型应该是 image/jpeg
而不是 image/jpg
, ,尽你所能 看这里.试试:
:type => 'image/jpeg'
您还可以列出所有可用的类型。 Mime::EXTENSION_LOOKUP
进入rails控制台。
例子::
管制员
class ImagesController < ApplicationController
def show_image
image_path = File.join(Rails.root, params[:path]) # or similar
send_file image_path, disposition: 'inline', type: 'image/jpeg', x_sendfile: true
end
end
路线
get '/image/:path', to: 'images#show_image', as: :image
意见书
image_tag image_path('path_to_image')
您需要让视图使用image_tag在视图上显示。
这里提出了类似的问题: 在私人存储文件夹中使用rails3.1中的carrierwave显示图像
不隶属于 StackOverflow