gpt4 book ai didi

ruby-on-rails - 如何使用 rails 3 显示路径在我的 Ruby on Rails 项目目录之外的图像?

转载 作者:数据小太阳 更新时间:2023-10-29 07:45:32 24 4
gpt4 key购买 nike

如何显示保存在项目目录外的图片?

有什么简单的方法吗?

最佳答案

我看到两种方式:

  • 在您的 rails 服务器之上,在生产中,有时在开发中,您必须使用像 apache 或 nginx 这样的网络服务器。有了这些,您可以为特定 URL 提供来自其他目录的文件。例如。您可以使 http://yourapp.com/images/ 从特定目录提供服务文件。在 rails 中,显示带有传统 image_tag
  • 的图像

Nginx 示例:

    # Find the right `server` section which you currently use to serve your rails app
server {
listen 80;

# Add this
location /images {
root /var/www/my/specific/folder;
}

location / {
#...
#... Here you should already some code to proxy to your rails server
}
}

With that, when you access to `yourserver.com/images`, nginx serve your specific folder and not your rails app. Then in your app view :

<%= image_tag 'http://yourserver.com/images/my_pic.jpg' %>
  • 如果您无法访问您的服务器设置,您可以使用 send_file

    从 Controller 操作提供图像文件

    在 Controller 中:

    class ImagesController < ApplicationController
    def show
    send_file File.join('/var/www/my/specific/folder',params[:name]), :disposition => 'inline'
    end
    end

    config/routes.rb

    match '/images/:name' => 'images#show', :as => :custom_image

    然后当您访问此操作时(通过您在 config/routes.rb 中定义的路由),您就拥有了图像。所以在你看来你用这个 URL 做了一个传统的 image_tag :

    <%= image_tag custom_image_path( 'my_pic.jpg' ) %>
    OR
    <%= image_tag custom_image_url( 'my_pic.jpg' ) %>

关于ruby-on-rails - 如何使用 rails 3 显示路径在我的 Ruby on Rails 项目目录之外的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9454340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com