Set path for original images using paperclip in Rails?

江枫思渺然 提交于 2019-11-30 11:09:42

问题


The situation

I have a simple model with an attached image using paperclip, which has a couple of processed styles for it (thumbnail, full, feature). At this point it works as it should, and makes a directory structure for each object in /public/assets/foo/, containing subdirectories for original, thumbnail, full, and feature.

The problem

I don't want the original (high resolution) images to be exposed for users to obtain. So I'm hoping there is a way to specify a different path to store the originals somewhere outside of /public/. Ideally paperclip should still be able to reprocess the styles using that original image as the source, as it does currently.

I'm also open to alternative suggestions for making the originals inaccessible to outside users. Whatever is the most practical solution here. Thanks.


回答1:


I would recommend using a custom interpolation that will place your original files outside the public directory. Something like this:


Paperclip.interpolates :maybe_public do |attachment, style|
  style == :original ? "private" : "public"
end

has_attached_file :image, :path => ":rails_root/:maybe_public/:attachment..."

This will save your :original files in a non-publicly accessible directory for protection, but still allow Paperclip access. And it will keep your thumbnails in the public directory for standard access.




回答2:


If it is acceptable, you could skip saving the originals, by setting the default style.

  has_attached_file :image,
                    :styles => { :normal => "800x600>" },
                    :default_style => :normal

If not, and you want to keep the originals, if you are using apache, you could use a .htaccess file to restrict the access to the originals directory

<FilesMatch "^\.(jpe?g|gif|png)$">
   Order allow,deny
   Deny from all
</Files>


来源:https://stackoverflow.com/questions/851226/set-path-for-original-images-using-paperclip-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!