【问题标题】:Displaying paperclip attachments stored in a non-public folder显示存储在非公共文件夹中的回形针附件
【发布时间】: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


    【解决方案1】:

    您需要更改传递给has_attached_file:url 选项,使其与您的图形控制器的路由匹配。

    例如,如果正确的 url 是 /figures/123 的数字是 123 那么你传递给 has_attached_file 的 url 应该是

    '/figures/:id'
    

    甚至

    '/:class/:id'
    

    由于:class 段将被插入到名称的复数小写下划线形式。如果需要,您还可以附加扩展名或文件名(但您必须稍微更改控制器代码以提取 id)

    【讨论】:

    • 我从您的回答中了解到,您建议创建一个控制器以运行一些逻辑来检查请求文件的用户是否有权读取它。如果是这样,通过使用 send_file 方法将文件发送到客户端。?
    猜你喜欢
    • 2021-09-08
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多