如何配置 Rails 来访问不在其常规目录位置的媒体资源?

发布于 2024-07-25 15:33:04 字数 295 浏览 6 评论 0原文

假设我有一个图像不在正常位置:

{appname}/public/images/unconventional.gif

但是在这里:

{appname}/unconventional.gif

我知道这完全违反了 Rails 约定,是不道德的,在任何情况下都不应该这样做,而且,为什么我什至会建议有这么蠢的事吗?

好的,现在我们已经解决了这个问题,假设我使用的是 Windows,因此符号链接是不可能的,那么如何进行设置呢?

Let's say I have an image that does not reside in the normal location:

{appname}/public/images/unconventional.gif

But instead here:

{appname}/unconventional.gif

I understand this is a complete violation of Rails conventions, is immoral and you should never do this under any circumstances and, furthermore, why would I even suggest such a foolish thing?

Ok, now that we have that out of the way, assuming I am on Windows and therefore symbolic links are out of the question, how is it possible to set this up?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

在梵高的星空下 2024-08-01 15:33:04

Rails 不提供这些图像,它让 Web 服务器提供这些图像。 您最好更改 Web 服务器的配置来处理这种情况。 例如,如果您使用 Apache,则使用 mod_rewrite 进行设置会相当容易。

让 Rails 提供这些图像会很丑陋,但是如果您在 routes.rb 中提供与 /public/images/unconventional.gif 匹配的路线,这是可能的,并且如果文件本身不存在。 例如:

map.connect "public/images/unconventional.gif",
  :controller => "static_image_controller",
  :action => "serve"

然后创建一个控制器 StaticImageController

class StaticImageController < ApplicationController
  def serve
    image = File.read(File.join(Rails.root, "unconventional.gif"))
    send_data image, :type => "image/gif", :disposition => "inline"
  end
end

警告: 如果您使用上述概念,请注意,如果您使用 URL 中的输入来决定提供哪个文件(使用例如,params[:file]),您需要彻底清理输入,因为您面临着将整个文件系统暴露给外界的风险。

Rails does not serve these images, it lets the web server do that. You had best change the configuration of your web server to handle this scenario. If you use Apache, for example, it would fairly easy to set up with mod_rewrite.

Making Rails serve these images will be ugly, but it is possible if you provide a route in your routes.rb that matches /public/images/unconventional.gif, and if the file itself does not exist. For example:

map.connect "public/images/unconventional.gif",
  :controller => "static_image_controller",
  :action => "serve"

And then create a controller StaticImageController:

class StaticImageController < ApplicationController
  def serve
    image = File.read(File.join(Rails.root, "unconventional.gif"))
    send_data image, :type => "image/gif", :disposition => "inline"
  end
end

Warning: if you use the above concept, note that if you use input from the URL to decide which file to serve (with params[:file], for example), you need to thoroughly sanitize the input, because you are risking exposing your entire file system to the outside world.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文