如何在Ruby on Rails中存储私人图片和视频

TK.*_*TK. 5 privacy file-upload ruby-on-rails image

这是一个故事:

  • 用户A应该能够上传图像.
  • 用户A应该能够设置隐私.("公开"或"私人").
  • 用户B不应该能够访问用户A的"私人"图像.

我打算使用Paperclip来处理上传.

如果我将图像存储在"RAILS_ROOT/public/images"下,任何猜测文件名称的人都可以访问这些文件.(例如,访问http://example.com/public/images/uploads/john/family.png)

我需要使用img标签显示图像,所以我不能放置文件,除了public.

如何确保其他人无法访问用户或组的图像?

(如果我用Paperclip无法做到这一点,那么什么是好的解决方案?)

P S*_*ved 8

您可以使rails服务器输出图像文件的内容.这是通过控制器操作完成的(大多数操作都打印HTML,但是这个会打印JPG,例如).

然后,您可以使用授权系统限制控制器级别的访问权限!

class ImagesController
  #Default show Image method streams the file contents.
  #File doesn't have to be in public/ dir
  def show
    send_file @image.filename, :type => @image.content_type,
              :disposition => 'inline'
  end

  # Use your favorite authorization system to restrict access
  filter_access_to :show, :require => :view, :attribute_check => :true
end
Run Code Online (Sandbox Code Playgroud)

在HTML代码中,您可以使用:

<img src="/images/show/5" />
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下,让web服务器为`send_file`发送的文件提供服务是合理的.看看Nginx中的`X-Accel-Redirect`或Apache中的`X-Sendfile`.有用的链接:[1](http://maxresponsemedia.com/rails/nginx-x-accel-redirect-setup-in-rails-3/),[2](http://thedataasylum.com/articles/how -rails-nginx-x-accel-redirect-work-together.html),[3](http://airbladesoftware.com/notes/rails-nginx-x-accel-mapping),[4](http:/ /www.therailsway.com/2009/2/22/file-downloads-done-right/). (3认同)

jdl*_*jdl 5

我会让 Paperclip 在后端使用 S3,将上传的文件设置为私有,然后使用“查询字符串请求身份验证替代方案”为我的图像标签生成 URL。

http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?RESTAuthentication.html


Cal*_*eed 5

这是我在类似应用程序中执行此操作的方法。

\n\n
    \n
  • 将图像存储在 Amazon S3 上而不是本地文件系统上。回形针支持这一点。
  • \n
  • 在回形针选项中将 :s3_permissions 设置为“私有”
  • \n
  • 在您的图像模型中,定义一个方法,让您输出图像的授权的、有时间限制的 URL。
  • \n
\n\n

我的看起来像这样:

\n\n
def s3_url(style = :original, time_limit = 30.minutes)\n  self.attachment.s3.interface.get_link(attachment.s3_bucket.to_s, attachment.path(style), time_limit)\nend\n
Run Code Online (Sandbox Code Playgroud)\n\n
    \n
  • 然后,只有当人们被授权查看图像时,您才可以向他们显示图像(按照您喜欢的方式实现)\xe2\x80\x93,而不必担心人们猜测/查看私人图像。它还可以防止他们在 URL 过期后四处传递(URL 中有一个令牌)。
  • \n
  • 请注意,您的应用程序需要一些时间才能为每个图像生成授权 URL。因此,如果页面上有多个图像,则会影响加载时间。
  • \n
\n