【问题标题】:How to display image from private folder inside View?如何在视图中显示私人文件夹中的图像?
【发布时间】:2014-03-30 03:46:11
【问题描述】:

我需要一个看似非常简单的快速提示。我在私人文件夹中有一些图片,想在我的视图中显示它们。

我找到的唯一解决方案是:

def show
    send_file 'some/image/url', :disposition => 'inline', :type => 'image/jpg', :x_sendfile => true
end

我读到:disposition => 'inline' 不应该触发图像下载并允许我在我的视图中显示它。问题是每次我触发show动作时,图像下载都会自动激活并自动下载。未显示 show 操作的视图。

如何在我的视图中显示该图像?谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 sendfile


    【解决方案1】:

    我认为问题出在type。来自文档:

    :type - specifies an HTTP content type
    

    因此,正确的 HTTP 内容类型应该是 image/jpeg 而不是 image/jpg,您可以使用 see here。尝试:

    :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(path_to_show_action) 放入,图像现在会显示在show 视图中。它显示在一个新的空视图中。所以,只显示图像,我需要在我的 show.html.erb 视图中显示该图像以及其他一些数据。
    • 使用send_file 行在您的控制器中添加不同的操作(也包括路由),然后您可以使用image_tag(path_to_this_new_action)。这样您就可以在其他视图中添加图像。
    • 我添加了不同的操作,但由于某种原因 send_file 没有通过。当我检查页面源作为图像源时,总是有/images/id_number,这是图像模型的show.html.erb 的url。
    【解决方案2】:

    我这样做的方式,我并不是说它完全符合书本,是我为图像创建一个根,并在控制器中创建一个动作来渲染它。

    例如,在 routes.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
    

    【讨论】:

    • 我对这种方法有一个问题,send_file "some/path/#{params[:image]}.jpg", :disposition =&gt; 'inline', :type =&gt; 'image/jpg', :x_sendfile =&gt; true 没有通过。 Ma 图像源始终设置在/images/:image 上,而不是我为send_file 指定的路径上。所以它设置在show.html.erbView的url上。
    • 我将添加一个工作示例供您使用。查看我的编辑。
    • 您应该调用 renderpic_path("filename.jpg") 或 "/images/filename.jpg" 以使其工作。
    【解决方案3】:

    您需要让视图使用 image_tag 来显示在视图上。

    这里提出了类似的问题:Showing images with carrierwave in rails 3.1 in a private store folder

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 2012-02-21
      • 2013-11-18
      • 1970-01-01
      相关资源
      最近更新 更多