How to store private pictures and videos in Ruby on Rails

后端 未结 4 677
情歌与酒
情歌与酒 2020-12-03 06:05

Here\'s a story:

  • User A should be able to upload an image.
  • User A should be able to set a privacy. (\"Public\" or \"Private\").
  • User B should
相关标签:
4条回答
  • 2020-12-03 06:40

    If you want to host files yourself, you can perform authentication at the controller level as has been suggested. One of my applications has an AssetController that handles serving of files from the 'private' directory, for example.

    One thing I wanted to add is that you should review this guide for setting up X-Sendfile, which will let your application tell the web server to handle actually sending the files. You'll see much better performance with this approach.

    0 讨论(0)
  • 2020-12-03 06:47

    You may make your rails server output the contents of image files. This is done via a controller action (most of actions print HTML, but this one will print JPG, for example).

    Then you may use your authorization system to restrict access on controller level!

    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
    

    In HTML code you may use:

    <img src="/images/show/5" />
    
    0 讨论(0)
  • 2020-12-03 06:55

    I would have Paperclip use S3 on the back-end, set uploaded files to private, and then use "Query String Request Authentication Alternative" to generate the URLs for my image tags.

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

    0 讨论(0)
  • 2020-12-03 06:56

    Here's how I did this in a similar application.

    • Store your images on Amazon S3 instead of the local file system. Paperclip supports this.
    • Set your :s3_permissions to "private" in your Paperclip options
    • In your Image model, define a method that let's you output an authorized, time-limited url for the image.

    Mine looks like this:

    def s3_url(style = :original, time_limit = 30.minutes)
      self.attachment.s3.interface.get_link(attachment.s3_bucket.to_s, attachment.path(style), time_limit)
    end
    
    • You can then show images to people only if they're authorized to see them (implement that however you like)–and not have to worry about people guessing/viewing private images. It also keeps them from passing URLs around since they expire (the URL has a token in it).
    • Be warned that it takes time for your app to generate the authorized urls for each image. So, if you have several images on a page, it will affect load time.
    0 讨论(0)
提交回复
热议问题