Rails paperclip gem - Get file from private folder

前端 未结 1 1121
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 06:08

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 &

相关标签:
1条回答
  • 2021-01-01 06:50

    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!

    0 讨论(0)
提交回复
热议问题