Simple Drag and Drop File Upload Tutorial - HTML, CSS & JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys how you going my name is diamond in today's video we're going to be having a look at creating a file upload input field um that supports dragging and dropping so we're going to be achieving this using the html drag and drop api and this right here is going to be the final product now as we can see i've got this drop zone area and i can either click on this area or i can drag in files so for example i can just drag in here a small image file and we can see we get a nice preview of that file alongside a small label which of course just describes the file name now if i was to drag in for example something different like an html file so i'll just drag this in right now for non-image files we're going to instead just see a gray background so of course you can modify this code and add your own image inside there for just generic files up to you and like i said earlier you can even click on this on this drop zone and instead choose your file in the traditional you know select window so so that's the final product now i do want to mention before going into this video that this solution supports multiple files but it's not going to be showing multiple files in the actual preview so it's only going to be selecting the first file which you choose in the preview and the reason for that is because this video is just meant to be a guide on how to use the drag and drop api and give you a foundation for how you might go about actually creating one of those or one of these file upload fields with drag support by yourself so if you guys do want to see a video of me you know creating a multiple file upload with drag support multiple thumbnails things like that let me know in the comment section below and i'll be happy to you know create one of those tutorials but for now this video is just going to cover the absolute basics of how to create something like this so um inside uh this tab right here we've got this uh you know empty html file so inside the text editor it looks like this i've simply just included a css file alongside a javascript file down here so both of those files are both empty so we're beginning from scratch to of course create the file upload so the very first thing we're going to be doing is we're going to be creating the html and the css first before moving on to the javascript so for the html we're going to be creating here a main container element so this will this will have a class of drop zone and like i said or like i said it's going to be a main container so essentially it's going to be representing this one right here okay so inside here there's going to be a couple of more elements the first one is going to be just the text to tell the user you know drop a file here or click to upload so we're going to be using a span for this with a class of drop zone underscore underscore prompts okay so once again using the block element modifier css naming convention but you can of course name these classes uh whatever you like and inside here i can say for example drop file here or click to upload something like that okay so now let's just stop here and then go inside the css and just style up those two elements so the first one is going to be the drop zone so i can target the the drop zone class and i can say max width of 200 px and a height of 200 px also so the reason for the max width and not the regular width is because this is going to make it responsive that way on mobile devices as the windows you know resizes down to less than 200 pixels the drop zone is going to just resize alongside it and of course the 200 here is to make it a nice perfect square we're going to also say padding and set this to be something like 25 px and a display of flex and align items of center and i justify content of center so these three properties are going to allow the text for the prompt to be vertically and horizontally centered okay alongside this we can say text align make this center and that's going to make sure that the actual text itself is aligned in the center so of course when it goes over two lines it's going to be centered okay um now we can apply some font family or some font changes here so for example i'm going to set mine to be quicksand and sans serif now these are of course completely optional up to you if you want to be applying these properties so a font size of 500 tends to look not you know pretty good in my scenario and a font size of 20px alongside that let's add a cursor of pointer to indicate to the user that you can actually click on the drop zone we can add a color of just a medium or a medium to light gray and a border of 4px and then dashed and then nine five seven eight and that is my decode green color um a border radius also of 10px tends to looks pretty nice on these drop zones so let's save this and refresh the page and we get something like this so as we can see uh we're we're pretty much like halfway there already in terms of the css but i did forget or i did make a mistake here on the font size so the font size actually needs to be font weight okay let's save this and try again and we get something like this so that is all for the drop zone however we need to add a modifier class to make it so you know once you drag over the element it's going to change the border style as you can see right there so to make this change it's quite straightforward we can just add a class so we can say drop dash zone and then dash dash and then we can call this one over so drop zone dash dash over is going to be added by the javascript when it needs to be added so of course when you drag out of the element or you cancel your drag things like that this class is going to be added so for this one we can just say border style and set the border style back to solid so now saving this and refreshing we can just select the container and add that class manually so drop dash zone dash dash over and we get something like that okay cool so now let's move on to styling up the actual thumbnail itself but i do want to just first up i do want to include inside here an actual input field so i'm going to say input type of file right here so the reason for this input type of file is it allows us to have a place where we can store the files that the user has uploaded alongside that or sorry that the user has selected and alongside that by having an input type of file it means that we can actually wrap this entire drop zone within a form element so something like this for example you can wrap the entire drop zone inside there just like that and the input type of file is of course going to work so you can actually submit the form like that if you don't want to go through an ajax or a fetch method of actually uploading those files so that's what i'm going to be using input type of file to of course store those files okay so of course this one right here also needs to be hidden so let's just go inside here and add a name of let's just say my file of course you'll need an attribute of a name to actually process the upload for regular form submission [Music] and a class of let's just go drop dash zone underscore underscore and then input so now of course saving this and refreshing we have something like this okay so let's go inside the css now and of course just hide that element so i'm going to say drop zone input i'm going to say display and set this to be none let's save this and refresh and now we get the exact same result as we did earlier okay so now let's move on to applying some styles for the actual thumbnails so back inside here um let's go inside the html and we're going to be removing uh the prompt just for now um the javascript is going to be handling all of this stuff so it's going to be removing the prompt by default once you choose a file but just for you know testing purposes here we can manually comment that line out and go down here now and we can add a div with a class of drop dash zone underscore underscore and then thumb so for both the image and the regular file examples it's going to be using a div okay so just keep that in mind and here we can just say data dash label equal to something like for example let's just say my file dot txt so this attribute here data label is of course a data attribute and it just lets us specify the label which will be displayed underneath the thumbnail so now saving this and refreshing we get something like this so of course a very expected result our div has no width and height so of course it's not actually being displayed so let's go back inside the css and apply some styles for the drop zone thumb class so we can say here drop zone underscore underscore thumb and for this one we're going to be setting the width and the height to be 100 that way the thumbnail takes up the entire width and height of the container minus the padding so we can also say here a border radius of 10px purely cosmetic up to you if you do want to have the border radius then make sure you also include an overflow of hidden that way our border radius is always going to be displayed even if our label which we're going to be adding very shortly overflows the bounds of this element okay anyway let's add a background color let's just do the same medium to light gray so triple c as we did earlier and this background color right here is going to be the color which gets displayed when you choose a regular file okay we can also set a background size and we're going to be making this a value of cover so using background size here of cover um it's there because we're gonna be setting the images um for the thumbnails through uh the actual background so we're gonna be applying the background dash image css property by the javascript to of course display the thumbnail image of your chosen image file so by having cover it means that the image is going to be taking up the entire space of the actual thumbnail element and it's not going to repeat itself and it's also going to maintain the aspect ratio okay and alongside this we can give a position of relative and this right here just allows us to position the label in the bottom of the actual thumbnail okay so of course back inside the example the label here is on the bottom so by having this position relative we are able to change that which we're going to be getting to very shortly but for now let's save this and refresh the page and we get something like this okay so obviously it's coming together for the thumbnail so now let's just go back inside the css and um make it so our label gets displayed so we can say here drop zone thumb then colon colon after so we're going to be using css pseudo elements here just to create a new virtual element for the actual label so we can say content and make this attr and pass through here data dash label so basically by doing this we're going to be displaying the text of the attribute data label so of course right here my file.txt is going to be the value for the content property okay we can also say here a position of absolute so this works in conjunction with our position relative up here in the parent element and it lets us do you know bottom zero for example and left zero so now it's going to be in the bottom left corner but we're going to also be adding a width here of 100 percent that way of course it takes up the entire width of the of the thumbnail we can also say our padding make this 5px top and bottom and 0 left and right let's give it a font color of white and a background of rgba00 and then 0.75 for a 75 percent opaque black okay let's give it a font size of 14px and a text align of center and now we should see our little uh text here myfile.txt we should see this in that nice black background on the bottom of the thumbnail so now saving this and refreshing we get this right here and that is it for the css and the html for the file upload field we can now move on to doing the javascript to of course make all of this work okay so moving on to the javascript um i just want to firstly go back inside the html and just remove the drop zone prompt comment so we can have the drop zone prompt reappear once again and just remove the thumbnail so the thumbnail is going to be generated through the javascript anyway so we can just remove this and this right here is our default you know setup when the page first loads up so now saving this and refresh and we have something like this so now we can move on to the javascript so inside here we're going to be doing this by firstly just selecting each one of our input with a type of file and the class of drop zone input okay so let's go inside the javascript and we're going to be saying document.queryselectorall and then pass through here drop dash zone underscore underscore import then we're going to be saying dot for each and then here we're gonna have holds of the input elements and of course right now this function is gonna be running for each one of our drop zone inputs on the web page because of course in this example here there's only one drop zone but maybe on your website you're going to have multiple of these drop zones on a single page so of course right here we're just selecting each one of those so for each drop zone input we're going to firstly just try and retrieve the drop zone container from the input field so let's go back inside here and we're going to be saying const drop zone element is equal to and then input element dot closest and then pass through here the class of drop dash zone so now using the closest method it's going to start at the input field and then it's going to be you know making its way up until it finds an element with the class of drop dash zone of course this one right here so now we have the drop zone element and in case it wasn't clear the input element refers to this one right here um so now we have both the input element and the and the actual drop zone container element um we can start adding a few event listeners okay so the very first event listener to add here it's going to be drop zone element and then add event listener and then pass through here drag over we're going to be grabbing hold of the event object right there and inside here we're going to be we're just going to be saying drop zone element dot class list dot add and then pass through here drop dash zone um dash dash over so here with the drag over events this is going to be running whenever the user drags over an image or file things like that okay so of course once we're inside here we're going to be adding the drop zone over class so that's going to be adding our modifier class to of course change the border style from dashed to solid so now saving this and refreshing and then dragging over a file we can see right there that of course the border changes to that solid feel so of course we can see there's a few problems if i was to drag out it doesn't change back and things like that but we're going to be fixing that very shortly but for now let's just go back inside the text editor and we can move on to adding some more event listeners so we're going to be saying here declaring an array we're going to be saying drag leave and then drag ends okay so these are two events but we're going to be applying these events at the same time so we can say dot for each and then here we can say type so of course type refers to one of these two and then we're going to be saying drop zone element dot ad event listener we're going to be passing through the type once again grabbing hold of the event object and we're going to be saying here drop zone element dot class list and this time we're gonna be removing the drop zone dash dash over um class okay so the drag leave event obviously happens whenever you drag outside of the actual uh you know drop zone and the drag end is going to be running um whenever you actually cancel a drag for example you press on the escape key to cancel the drag okay and i'll just be replacing these two with the double quotes and of course here we're just removing that class to of course go back to the dashed border let's save this and refresh and now if i was to drag over a thumbnail and then drag away we can see of course it goes back to the dashed version and also if i was to press escape escape on my keyboard it also goes back to the dashed version so those two event types are working we can now move on to the main part of this tutorial and that of course is going to be handling the actual dropping of the files so we can say here once again drop zone element dot add event listener and here we're going to be adding the drop events we're going to once again be grabbing hold of the event object and inside here i'm not going to do anything just yet but i do want to just console.log the event object okay so let's just save this and then refresh the page and then attempt to drag in our thumbnail i'm going to drag this in over the drop zone and let go and we can see right there the browser is going to open up the image um in the actual you know web page so that is the default behavior when you drag in a file so in order to stop this from happening we have to go back inside here and we need to be adding a few prevent defaults so inside the drag over you need to say up here e dot prevent default just like that and do the same thing for the drop event so that one right there so adding the prevent default for both of these event listeners is going to prevent that default behavior from occurring so now saving this and refreshing let's just go inside the console here and then drag in that same file this time we see nothing happens and of course in the console we get the drag event object so in this drag event object and this data transfer property is pretty much the most important one for this tutorial and the reason for that is because it's got right here a files property okay so this right here is a file list containing each one of our files so as we can see here it currently says a length of zero now this is actually i believe after doing a bit of googling um this is a this is a bug in google chrome where it should actually be showing the updated file list so let's go back inside the the javascript here and say console.log this time saying e dot file list directly so now saving this and refreshing we can see now if i drag it in we get nothing so let me just figure out why okay so it needs to be e dot data transfer then dot files okay let's try again refresh and then drop this in this time a length of zero and of course we can see right there we have the file object so like i said uh the previous example with the logging to the console that appears to be a bug but if you log it out directly we can see we do in fact have a list of files inside there okay so with that being said let's go back inside the text editor and remove this console log and now we're going to be doing this we're going to be saying if e dot sorry if if e dot data transfer um dot files dot length so if we have you know at least one file that was dragged in we're going to be saying here input element dot files is equal to e dot data transfer dot files so this right here is essentially taking our list of files so our actual file list object is taking a list of files from here and then assigning it to the input element itself so now when you submit the input element or sorry when you submit the form with the input element inside of it it's going to be submitting the files which you selected from the drag event okay so we can then say down here update thumbnail so we're going to be defining this function very shortly but we're going to be calling a function called update thumbnail we're going to be passing through the drop zone element and then we're going to be passing through the first file so e dot data transfer dot files at index zero and this is why our thumbnail preview only shows the first file which you selected okay so now down here we can say drop zone element dot class list dot then remove and once again remove the drop zone over class so now let's go down here and just to find that update thumbnail function real quickly we can say function update thumbnail and then it's going to be accepting like i said a drop zone element and also our first file right there so now i'm going to console.log i'll just log out the drop zone element alongside the file okay just for now let's save this and then refresh the page and then of course choose for example one file we can see right there we get the drop zone element and also we get the file okay so everything's working perfectly fine now um also those two for example uh i might just drag in multiple files here so i'll just um i'll just console.log input element.files okay so list the list of files on the input element itself okay i'll log that out i'll refresh and then i'm going to be selecting multiple files here so i'll just go inside here real quickly and select multiple files okay so i've got two right there drag this in and now you can see here we get the file list right up here we get two files zero and one length of two and of course the function only received the first one the vhost intro.html okay cool let's go back inside here now remove this remove this console.log um then go down here and move on to doing this update thumbnail function so um inside here the very first thing to do is we need to grab the hopefully existing thumbnail element so the element which we removed earlier we need to either grab an existing one or create a new one so let's go back inside here and say let's thumbnail elements equal to uh drop zone element dot query selector we're gonna be selecting the uh the drop dash zone underscore underscore thumb class okay so obviously when you very sorry when you when you call this for the first time this is going to return undefined since there is no element with that with that class but on the second time it's going to exist so we're going to be saying here if there is no thumbnail element then we're going to be creating it so i'll just say here you know first time there is no thumbnail elements so let's create it okay something like that so inside here we can then say thumbnail elements dot sorry equals document dot creates element and pass through here of course div then we can say thumbnail element dot class list dot add let's add the class required so that is drop dash zone underscore underscore thumb okay then we can say uh drop zone elements dot append child and pass through here our thumbnail elements okay so now of course we're just appending the thumbnail element to the actual container of course this one right here so now if i save this and refresh we should see the actual thumbnail being created so i'll just select a file again and we can see we get that right there so clearly there's a one minor issue here and that is the prompt still exists so let's remove that prompt if it is there currently so let's go back inside here i'm going to be saying just below that block of code we're going to be saying if drop zone elements dot query selector then we can say drop dash zone underscore underscore prompt so basically if the prompt currently exists within the drop zone element then we can just say once again query selector and we can say dot remove to remove that element so now saving this and refreshing we can see now if i drag it in the prompt gets removed on the first time similar to this condition right here so i might as well just say copy and just say first time remove the prompts and that's basically it okay cool so now let's move on and we can just say down here thumbnail element dot data set dot label is equal to file dot name so i do want to mention here that the file object here is an actual you know proper file object which means i can for example here console.log and i'll log out the file and then save this and refresh and we can see if i drag it in the file looks like this so we're just grabbing the name property from the file object of course gauge.html and then we are simply just setting that to the label data attribute which i showed earlier and of course it is being grabbed by the css label and of course being inserted just just right there okay cool so um i might just copy and paste some jsdoc which i prepared earlier so i'll just copy this and add it up here i probably should have done this uh much earlier on but um there we go so now with this jstoc we can see we have the file type so now if i was to say file dot and then name it gives us the nice autocomplete for the name so that is adding the actual label okay and the very last thing to do here is of course actually display the image if it is an image okay so we can say here show thumbnail for image files and here we can say if file dot type dot starts with and then pass through here image forward slash okay so let's go back inside the browser real quick and we can see here in the file object we have the type and for the image files i'll just drag one in real quickly here um so for image files we can see for example here the thumbnail we get type image slash jpeg so of course we're just checking if the type starts with image if it does then we're going to be of course displaying that image so we can say here const reader equal to a new file reader so this file reader right here allows us to of course read files and we're going to be reading the file um to add to a data url okay so we can say here reader dot read as data url so this gives us a base64 data url for the file i'm going to be passing through here the actual file just like that and then this is actually an asynchronous call so we need to say reader dot on load and basically we're going to be running this function right here once the reader is complete or done with reading the file so essentially we can access it using reader.result so we can say here thumbnail elements dot style dot background image one second dot background image equal to then we can say right here using the backticks template strings okay we can say url pass through here inside double quotes sorry single quotes putting a dollar sign and the two curly braces we can pass through here reader dot result so like i said reader.result is gonna contain the base64 data url representing the image and it's going to be available once the reader is complete reading the actual file okay so now saving this and refreshing we should see now if i was to drag in a thumbnail it appears right there okay so in the instance where you know for example the user has chosen an image like this and then they decide to change to using an actual html file we can see it still stays there the background image so let's fix that up right now let's go back inside here then say else and here we can simply say thumbnail element dot background image is equal to let's just make this now so of course this is going to run whenever the type is not of image so now saving this and refreshing and then dragging in an image file for example the same thumbnail and then let's go back inside here and drag through a html file we can see now of course it gets changed and that's basically how it's going to work okay so the very last thing to do here is to make it so when you click on the actual drop zone it gives you a manual selection file input prompt so in order to achieve this let's go back inside the text editor i might just go up here and just remove this console log of that file and let's go up inside the main event listener up here or the main for each sorry um and then inside here we're going to be adding an event listener once again to the drop zone element so we're going to be saying drop zone element dot add event listener and pass through here the click event so basically whenever the drop zone element gets clicked on we're going to be running this function inside here and basically we're going to be saying input element dot click so essentially we are programmatically uh clicking on the input element whenever you click on the drop zone so now saving this and refreshing and now clicking on the drop zone we can see right there we get the file selection prompts i can of course choose a file and now we need to make it so when you of course choose a file it's going to display the thumbnail so let's go back inside here and we're going to be saying right down here we can say input elements dot add event listener we're going to be listening for the change event on the actual input field itself and this is going to run whenever the input bill out so whenever the input field value gets changed so we can say right here we can just say if input element.files dot length you know is is more than zero then we can say update thumbnail we're going to be passing through here the drop zone element and along the side that we can just say input element dot files input element dot files and pass through like we did earlier the first file in the file list if you want to support multiple files here you need to simply add the multiple attribute to the input file just like that okay so now i'm not going to do that let's just uh save this and then refresh the page choose a file once again and we can see it now displays as the thumbnail so that is the main chunk of the work for the drag and drop file upload but you might be wondering you know how do you actually upload those files once you've got them inside the input field so to answer that question there's going to be two primary ways you can do this so the very first method and probably the uh probably the easiest way to achieve this would be to wrap the entire drop zone right here inside a post form so something like this so if you're using for example php as your server type technology we can say for example dot forward slash upload dash file dot php obviously this is going to change depending on your own situation just an example and then here you can just say ink type and make sure this is set to multipart form data and then inside here inside this form you can simply just copy and paste the drop zone and it should all work as it would normally so if you're not too sure how to upload the file using a form just do a quick google online and figure out you know how to actually do it but essentially the input type of file needs to be inside the form and then of course here you can say input type of submit to actually of course submit that form and do whatever you need to do the second way to upload the files or the file would be to upload it asynchronously using either ajax or the fetch api so i've got a video on uploading files with the fetch api if you're interested and hopefully that video should cover most if not all of the uh of the content to actually upload that file asynchronously and that is how to create a uh a file upload field with with our drag and drop capabilities um thanks for watching guys and i'll see you later you
Info
Channel: dcode
Views: 44,631
Rating: undefined out of 5
Keywords: code, coding, programming, tutorial, introduction, beginner, walkthrough, guide, software, development, simple, easy, english, with, example, examples, developer, lecture, recording, how, to, web, website, app, application, js, javascript, es6, ecmascript2015, drag, dragging, drop, dom, document, object, model, event, events, addeventlistener, file, files, filelist, api, ondrag, ondrop, uploading, ajax, fetch, forms, form, submit
Id: Wtrin7C4b7w
Channel Id: undefined
Length: 38min 7sec (2287 seconds)
Published: Tue May 05 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.