Last night was a really long one. Why? Because I couldn’t find enough information on how to make nginx handle uploads (using upload module and upload progress) and include carrierwave on the equation to handle files after they have been sent to the server.
Maybe I didn’t search enough, maybe I found only the old deprecated stuff, but after compiling these sources I think I came up with a decent solution.
First off, let’s compile nginx with some upload sugar.
1 2 3 4 5 6 7 8 9 10 11 12 | |
So the module is there, we need to make it come to life in nginx.conf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
This is from a server using unicorn to serve the rails app, if you need some help getting started with nginx and unicorn this is a good place to start. And I really recommend that you read upload module’s docs carefully.
The important bits are the ones starting with “upload”.
The way it works is upload_pass routes the request to the @app location after the upload has finished it’ll pass the form fields you set with upload_pass_form_field along with the ones we’ll be using to show the file to carrierwave.
Now restart nginx and you’re good to go. #NOT
As soon as you try to upload anything nginx will complain about permissions or directories it could not found so lets fix that.
I’m using 1 level deep directory hashing (set on upload store) so I’ll have to manually create the directory structure and chown it to the user that runs nginx workers (in my case is rafa:rafa).
1 2 3 | |
Now to your rails app. I’m using mongoid, but this applies to any orm.
1 2 3 4 5 6 7 8 9 10 11 | |
Lets create the route to recieve the request after the upload is handled by nginx.
1
| |
And the action to save it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
The trick here is to simulate a ActionDispatch::Http::UploadedFile being passed to carrierwave.
This will send the file to the right place, but I still have some quirks to solve. Like the temporary dir cleanup task and the content_type validation. Once I get the hang of those I’ll update this post.