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.
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:
… and the request will be routed to the
avatarsaction in theuserscontroller (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):
Now if you type
localhost:3000/users/7/avatarsinto 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),
But now we can generalize our code in UserController to handle any user, like this:
Now we can test
localhost:3000/users/7/avatarsagain to be sure that we haven’t broken anything.Cheers!