Direct Uploads with Rails ActiveStorage

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] what's up guys this episode we're diving into direct uploads with active storage using digital ocean spaces and all of this is going to apply equally to Amazon s3 if you want to use that instead so what we've got here is a file upload field where we can just upload some screenshots or whatever and here we just select those files and then the direct upload JavaScript is going to intercept the form submission it will look for any of those file fields that are marked as direct upload it will upload those to the active storage endpoint and then replace in our form and we'll insert two hidden fields with the signed IDs of those active storage attachments so that our form will be submitted and just receive the IDS and then attach to those already uploaded files so when we click create post we'll get progress on these files you're going to see them upload and then the form will submit after they have been successfully uploaded so that is all we're going to implement in this episode but it is a fair bit of different things because we have to worry about setting up our spaces correctly our course config our JavaScript and our form and making sure that of course we have our model set up with active storage so there's quite a bit to do in this episode so let's dive in so I'm going to walk you through setting up everything from scratch what we've used here to create our new rails app is the jump start template that I've created before which installs devise bootstrap and a few other things just to get us a bare-bones application so I've already run that with the template and we've got an application here called direct uploads and we need to run rails active storage install because it doesn't include it by default that might be added in the future and we can run rails DB migrate to make sure that we have those active storage migrations run and then we can generate some sort of model that we're going to use I'm going to create a scaffold for this can have an easy example we'll have posts that can have multiple attachments on them and that will be titled body as text and then we can run rails DB migrate for these and if we open up our editor we'll be able to go into the routes file we will set the route to posts index we'll go to the post model will say it has many attached files or something like that so this will be our active storage attachments and then we can go into our post forum we will have a field here we'll just grab this one this will be a file field for files so B for files as well and then we're going to say multiple it's true because we want you to be able to upload multiple files and then no we can go into our post controller and accept that where we'll have files which would be an array of strings so we'll pass in the signed IDs using the JavaScript so we'll have that as our purim and then our post shown at HTML ARB we're going to want to print out those files that have been uploaded SaLuSa scrap body save files and files dot each do file we'll set up to loop through those and we will link to file dot file name and then directly to the file so if you click on it it will open up that file you could also say maybe target blank so it opens up in a new tab if you like but that is up to you so then we're going to need to go into our storage mo and create one of these locations so that we can upload files so what I'm going to do here is name one called spaces it will be Amazon s3 and instead of using the rails credentials file we're just to use as three key is an environment variable that I've already set up and we'll do the same thing for this one we'll just change it to s3 secret and then our region is going to be NYC three bucket it was going to be called go rails and one last thing we need for digitalocean is the endpoint option here which will be NYC three digital ocean spaces calm in at the beginning here we want to say HTTP colon slash slash so it knows to use SSL for that connection so that's going to set up our bucket for us and then we can go into our development environment and say we want to use that spaces service so that we can have that those files uploaded there now we're going to need to include the JavaScript for this so we're going to open up application J s and then we're going to require the active storage JavaScript here but you can see we already have in our file so that active storage javascript is going to be what will fire off the events for the direct uploads and handle all of that for us and then that's going to be where we can hook in to insert those file upload file names and progress bars so we can see that progress so this is going to be our first step you can also require this in web Packer if you wanted with the NPM package which you would have to install separately but this will work and we're easy enough in the asset pipeline so we're gonna use that and then we're going to grab some JavaScript and CSS from the active storage documentation for the event listeners and for the CSS of those progress bars so we're gonna grab this we're going to just drop it in here and say let's just require itself to keep this simple you would probably want to put this in a separate file like Dave suggests direct uploads yes but in our case we're just going to drop it here and we can take a look at how this works pretty easily so this direct upload initialize event is going to fire on a target and that target will be the file upload field that is in your application and marked as direct uploads so in our case if we go to the post forum we can go to the file field and we can say direct upload is true so if we save that and start a rails app we can go to the new post forum and if we inspect this that data attribute will have been added for us or we say direct upload it's true rails is going to interpret that and say okay you actually want the data direct upload URL to be installed and so this will add the data attribute for us and it will point to the rails active storage direct upload zero and we can see here it's multiple and the name is post files and square brackets so it handles multiple correctly and so then our JavaScript will just be the piece that will make this actually functional so that JavaScript that we pasted in here is important because this is going to run this whenever it initializes a direct upload so this initialize event is going to fire for every upload that you added so the multiple is true is going to fire this as many times as the number of files you chose now we're pulling out the target so that's going to be the file upload field and then we're going to insert a JSON HTML before it so what's going to happen is this HTML snippet will be inserted before your file upload field say ten times if you uploaded ten files and so that's going to insert these so we can have something on the page to show those uploads then when they begin starting we're going to remove the pending class that's about all that really happens for that and we're using this direct upload ID because with this ID we can reference the correct HTML snippet so that's really important and you're going to want to make sure you have this ID no matter what as long as you change the snippet or anything keep that ID on there then once the actual progress it will go and set up the progress and basically this is just styling the width of the progress bar so you can see that here we're changing that style width in that one nothing too fancy we just need to select the proper element for that upload and then change its width every time it progresses and then if there's an error in this case it's going to add a red bar around the file upload which will be the error and you might want to do other things so you can go ahead and handle that in here and then the last one is if it's finished it's just going to add at the complete attribute or a class to the element so that's all there really is to that now this is going to work best when we have the Associated styles so we're gonna grab those as well and you can go and modify these just like you might with the Java Script here so we're gonna go to the Style Sheets application SCSS just drop this here at the bottom so we can see that and then lastly we need to go and add the AWS SDK s3 gem this is going to allow us to generate a token so that we can in our browser upload to our bucket correctly and even if you weren't using direct uploads you would need this gem so you could actually hit their API and upload the file from the server so with that we are almost done except if we were to try to upload a file now after we install that gem and restart a rail server if we were to try to do this we're gonna get an error you can see that with the red outline here and our error says basically 403 forbidden and we have a cores problem where we get the response to preflight request does not pass access control check and so what's happening is it's saying that the digitalocean spaces domain is not allowed to have this file uploaded to it because has not accepted files from our domain and so we have to go into our settings in our course configuration for our bucket and then set this up now the problem with this is that the origin does not allow localhost 3000 currently and digitalocean spaces so we have to upload a file of XML instead but if they fix this soon you'll be able to just go in here and then check off these boxes and click save options and you would be good to go so this would allow you to go ahead and create in this course configuration so you can get files out of it you can update files delete files create new ones and also grab just a metadata the file with the head request but we're going to have to create this XML file locally on our machine and then upload it to digital ocean spaces because we are not allowed to use this domain unfortunately in the browser so we need to create a course dot XML file this is what we're going to upload to our space so that digital ocean spaces will actually parse this out and allow these rules so this is an example here we have a loud origin localhost 3000 you can add multiple of these so if you wanted to have your production site as well like say go rails com you could do that and then you can set your allowed methods and your aloud headers now in our case we're going to want just the say get put and post maybe even head but we don't want our browser to be able to go and delete files from our bucket so we're going to allow you to put post and get files but we're not going to allow you to delete and we can then go and install a command called brew install s3 CMD and so if you're on a Mac you can use this if you are not go look at the s3 CMD or s3 command installation instructions and install that on your machine then you can you s3 command - chefs configure this commands gonna ask you a bunch of little questions like what's your access key and secret and then it's going to ask you what endpoints you want to use this blog post I'll linked in the notes below just walks you through that basically you want to give it your access key your secret you can leave the default region as the US it doesn't care about that the s3 endpoint is where the region gets specified because it says that in the domain so you're going to want to have your NYC three digital ocean spaces com change NYC three if you're using one of the other locations for spaces and same thing for the template for the bucket name you can just specify this change the NYC three to your equivalent one or you can leave this all as the defaults for Amazon s3 if that's what you're using then we can then go to our command line and run this command s3 command set cores give it our cores dot XML file we just created point it to our bucket if we run this it should upload I was receiving a 500 error as I was recording this but it was working and uploading that to digital ocean spaces when it uploads successfully you should be able to refresh this page and see localhost 3000 here and you're allowed methods and then once that's ready to go you should be able to test this out and do a file upload so then we can upload a file I'm going to grab a screenshot here we'll click upload post and that will go and upload and you will see that it gets uploaded successfully so here you can see a bunch of files that I've uploaded through that we can go edit post we can grab another file and then we can go and upload that and it will upload correctly so all of that is working and it handles everything like we would expect all these files are going directly from our browser to digital ocean spaces or Amazon s3 and they're not being uploaded to our server and then uploaded again to that service they're going directly from our browser to the third-party service which is why you have to deal with all that course configuration junk but that is it that is all you have to do for this in the active storage documentation has that really great JavaScript snippet and CSS for those upload progress bars you're free to edit those as much as you want they're really really simple and you can go and make those function however you might like but the base functionality of showing the progress and all of those files is built in there so you can grab that paste it in and then start tweaking it to your heart's content so that's all there really is to it for direct uploads it's very very simple and then if you ever want to integrate this into your applications that's all you have to do is the standard setup and then turn on basically direct uploads and add a little bit of JavaScript and CSS to make the form a little prettier so that is it for this episode I hope you guys enjoyed it and I will talk to you in the next one [Music]
Info
Channel: GoRails
Views: 12,995
Rating: undefined out of 5
Keywords: Ruby, Ruby on Rails, Rails, Javascript, HTML, CSS, Servers, Databases, active storage, activestorage, rails activestorage, direct uploads, activestorage direct uploads, rails direct uploads
Id: S-E2TNkXBV8
Channel Id: undefined
Length: 15min 52sec (952 seconds)
Published: Thu May 31 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.