Rails paperclip gem - Get file from private folder

孤者浪人 提交于 2019-11-29 15:34:17

问题


I'm using paperclip to upload files to my server. If I don't specify the path, paperclip saves the file to a public folder, and then I can download it by accessing <%= @user.file.url %> in the view. But if I specify the path to a non-public folder, it's not possible getting the file from the view, obviously.

I would like to know some way to download the saved files in a private folder, from the web and from a ruby script.


回答1:


The first thing we need to do is add a route to routes.rb for accessing the files.

Edit routes.rb and add the :member parameter in bold:

resources :users, :member => { :avatars => :get }

Now to get the avatar for user 7, for example, we can issue a URL like this:

 localhost:3000/users/7/avatars

… and the request will be routed to the avatars action in the users controller (plural since a user might have more than one style of avatar).

So now let’s go right ahead and implement the avatars method and add some code to download a file to the client. The way to do that is to use ActionController::Streaming::send_file. It’s simple enough; we just need to pass the file’s path to send_file as well as the MIME content type which the client uses as a clue for deciding how to display the file, and that’s it! Let’s hard code these values for the better understanding (update the path here for your machine):

    class UsersController < ApplicationController
      def avatars
       send_file '/path/to/non-public/system/avatars/7/original/mickey-mouse.jpg',
       :type => 'image/jpeg'
      end
    end

Now if you type localhost:3000/users/7/avatars into your browser you should see the mickey image.

Instead of hard coding the path in the avatars method, we obviously need to be able to handle requests for any avatar file attachment for any user record. To do this, configure Paperclip and tell it where the files are now stored on the file system, and which URL we have configured our routes.rb file to use.

To do this, we need to add a couple of parameters to our call to has_attached_file in our User model (user.rb),

    has_attached_file :avatar,
    :styles => { :thumb => "75x75>", :small => "150x150>" },
    :path => 
    ':rails_root/non-public/system/:attachment/:id/:style/:basename.:extension',
    :url => '/:class/:id/:attachment' 

But now we can generalize our code in UserController to handle any user, like this:

    def avatars
      user = User.find(params[:id])
      send_file user.avatar.path, :type => user.avatar_content_type
    end         

Now we can test localhost:3000/users/7/avatars again to be sure that we haven’t broken anything.

Cheers!



来源:https://stackoverflow.com/questions/13722472/rails-paperclip-gem-get-file-from-private-folder

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