【发布时间】:2014-08-31 13:41:22
【问题描述】:
我的难题是如何在 html 页面中嵌入其来源在整个 Internet 上不可用的图像。
假设我在 Rails/Paperclip 设置中有以下模型:
class Figure < ActiveRecord::Base
has_attached_file :image
...
end
class User < ActiveRecord::Base
... (authentication code here)
has_many :figures
end
在控制器中:
class FiguresController < ActionController::Base
def show
# users must be authenticated, and they can only access their own figures
@figure = current_user.figures.find(params[:id])
end
end
在视图中:
<%= image_tag(@figure.image.url) %>
当然,问题在于默认回形针设置图像存储在公共目录中,任何知道链接的人都可以绕过身份验证/授权访问存储的图像。
现在,如果我们告诉 Paperclip 将附件存储在私人位置:
class Figure < ActiveRecord::Base
has_attached_file :image, path: ":rails_root/private/:class/:attachment/:id_partition/:style/:filename",
url: ":rails_root/private/:class/:attachment/:id_partition/:style/:filename"
...
end
然后就很容易控制图像被提供给谁:
class FiguresController < ActionController::Base
def show
@figure = current_user.figures.find(params[:id])
send_file @figure.image.path, type: 'image/jpeg', disposition: 'inline'
end
end
这个动作的效果是在自己的浏览器窗口/标签中显示图片。
另一方面,image_tag(@figure.image.url) 会产生路由错误,这是可以理解的,因为无法访问源!
因此,有没有办法通过image_tag 在常规 HTML 页面中显示图像,同时仍限制对其的访问?
【问题讨论】:
标签: ruby-on-rails paperclip attachment