Securely Display an Image Uploaded with paperclip gem

被刻印的时光 ゝ 提交于 2019-12-03 15:46:24

You could use send_file. Assuming you have secure_image action in your routes:

resources :posts do
  member do
    get :secure_image
  end
end

and following method in corresponding controller:

def secure_image
  send_file Post.find(params[:id]).some_image.path
end

you can use protected images in your views:

<%= image_tag secure_image_post_path(@post) %>

What's happening here: usually Rails (or nginx or apache) sends static files directly bypassing security checks in sake of speed. But request for secure_image action goes through whole Rails' stack, so it is protected with your authentication system.

You can make an action in one of your Rails controllers that validates the user's identity/authority to view the image. Instead of rendering a view, the action can then send the image in its http response using send_file:

http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_file

Then once you get that action working on its own and you can see that it displays an image in your browser, you can make img tags that point to the url of that action.

Each image would have its own URL, but you would be in total control of what that URL is and who can access it.

You can convert image into Base64 format and while displaying can convert that into image.

Other technique is to watermark your images to make sure image is useless for others.

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