HTML5 and JavaScript: How to use the file input control

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we're going to build functionality that enables a user to select files and upload them to a server to upload a file there are many techniques the most prominent among them is to use a an input element of type file just to demonstrate what it does without any code I'll create a blank HTML file and I'll just have a form tag within which I'll include an input of type file and a submit button that's all my code is I haven't written any JavaScript or CSS let's see what this achieves out of the box now to be able to upload something I need a server so I've set up this application to run on port 8080 8 on a web on a local host web server out-of-the-box just those lines that we wrote give us these two buttons this is the upload button and this is the file control if I click the Browse button I'm able to select files from my file system if I select a file you will note that I'm I'm pressing the shift key I'm not still able to select more than one file by default if you don't write any code this is the default behavior the file input control lets you select just a single file I'll select a file and by default it displays the name of the file one important property of the file control of this input element is value let's see what the value property for this file control reads if you check the value property it has the name of the file prefixed with a fake path this is the fake part this is a little string that gets prefixed to any file that you select the reason for this fake path is that we do not want the web the designers of the world wide web rightly thought that it would be a security hazard to reveal the actual part of a file on a client or a user's file system to a web application server because otherwise slowly I could just have the user upload files from different places and get a feel or an outline of the directory structure and then imagine what that allows me to do when the user is asleep or when they're not using the application I can write things that or even when they're using my application I can write all kinds of things that read files from their file system if I know the locations of different parts on the file system so this string is attached by default so that's a prominent property value now if I were to make a post request I will need to add another attribute to the form called egg type which stands for enclosed type and this I'm telling the form or I'm telling the server that this form encloses this mime type of data and the mime type when you're using an file input control you could select one file or potentially multiple files I haven't taught you how to select multiple files which I'm going to do in a bit but you could select many files and all those files are chunked or all those files are serially appended one after the other and there is a boundary drawn in between each of those files and that whole composite unit is packed like a parcel and that's denoted by a mime type called multi-part form data multi-part slash form - data so I'm telling the server you must expect in this post request this mime type so it knows how to parse the data now adding just this much allows you to select and upload a file to a server that's all you don't need any JavaScript or anything else so I'll select a file I cannot right now select more than one file eh I'm pressing the shift key but I can't it doesn't allow me to select more than one file let me select just a single file and sorry let me first refresh it just to make sure I have the latest code and let's just verify if if I have the latest code yes I've got the latest code let's look at the network tab I will select a file and click upload of course now it has posted to an endpoint called index dot HTML on the server but the server doesn't have any code to handle the post requests so it says this method is not allowed which is fine but all I wanted to do was to look at the body of the request and show you what it looks like or if you've got any file actually posted if you look at where we posted we posted that index dot HTML we made a post request and the request had a special header saying the content type is multi-part slash form data and that it had some random string this string is the boundary that is that I was just talking about that is inserted in between each file and the param stab shows you the request body right now nothing was posted no file was posted ideally it should have posted that file but let's try that again okay and if I upload this the param tab should have had the body of the request anyway we'll get to that in a moment now to select more than one file all you have to do is add an attribute to the file input element called multiple it doesn't need to have a value you can just leave it as as a standalone independent attribute and this simply that attribute will now allow us to select all of these files and it says you have three files and I can upload these files and now again we don't have any code handling it so this method not allowed status response is perfectly fine I want to look at the body of the request and see if the stuff was actually sent ok I don't know why this stuff is not sent usually it is sent but as we develop this example we get to know why I might be missing something and it's hard to think while making these videos so let's carry on with example now one other property that I want to make you aware of of this file input control if you select more than one file let's say I select all of these and let's look at let's get the file control and again look at the value the value property has just the first file that you selected and it has a fake path it's just a string that has this is just a string that has the fake part of the fire so this is no good it's not helpful I want to get some metadata about all the files I selected and that is available to us with the property files there is a property named fires this is a file list a special kind of list that tells you how many files are selected and some metadata about each of these files a couple of things to note about these this file list is not an array so you can't use array methods like for each or map or reduce on this file you can if you wanted to use those methods you could copy this file list into an array using array dot from so you could do something like I'll just add a script and you could do something like array dot from and give it the input control files and then you can call for each or map or reduce on this array but you can't call it on the files object the files object is simply a read-only list that you can't add do you can't add any files to it you can't modify any existing files in it you or you can't remove the files from it because that's a security implication think of the security hazard that would entail if the code on the client side was allowed to manipulate or add or remove to this remove from this file object then any script running on any page could add anything to this file object or think of third party scripts you have adds you place on your page or Google Analytics or share this plug-in or different kinds of plugins those are written by somebody you don't know and they inject their code into your applications code so think of what they could do if this were allowed so the file list is a read-only kind of list that you can't attach anything to and let's just look at the files property even more closely each of these has an interface called file that has these five properties one is the UNIX timestamp of the date and time that this file was last modified this is the name of the file just the name not the whole path and this is the number of bytes of the file the size of the file in bytes and this is the mime type and this is a extension of WebKit extension which is helpful if you want to select a folder and a folder may have subfolders let's say you selected a folder and then that folder would entail selecting all the folders and files and those folders so each item would be either a file or a folder and the whole relative path that is the path of that item whether a file or folder relative to the folder you selected would be shown here if what I'm saying doesn't make any sense forget it it's not relevant it's not a standard feature anyway it's not available on any browser that doesn't that isn't powered by the WebKit engine the relevant properties out these four and you can use this one also but the WebKit relative path but I'd suggest that you don't use it in another video I'll show you how to use it it's pretty simple it's not difficult and then you have that for each file this is an image file similarly this is another file and then you have the length so there's nothing you can do with this file list it's a read-only thing let's create a new MVC project and write some server-side code and I don't need any of this so I'm going to delete everything from this project I'll just delete all the bundles everything I'll leave the jQuery bundle but delete everything else I don't need any bootstrap or anything else okay I need a handle I'll just leave it in I need a default route I'll leave that in I don't need any of the scripts I'll leave the jQuery intellisense and jQuery and the min and wind map I don't need any of these files I don't need moderniser I just need the jQuery file I actually don't even need these yeah I won't get into what all this is but I just need the jquery files I'll leave that in and let's delete everything actually I'll delete even the view start okay and go to the home controller I'll delete all of these and I'll just create an action card upload this would return of view let's add a view it'll be called upload it'll be empty I don't want any layout page it's not a partial view once I have the view I'll delete everything and copy and paste this HTML into this view now this is without any JavaScript let's see what gets posted to the server if I make a post action with the same name now obviously you need to have an argument otherwise c-sharp the language rules do not permit a method to have the same name two methods to have the same name and also the same parameter signatures so what do I want to put here so that it gets bound to the file input control first to do that I need to give a name to the file input control because MVC binds things or name and now I need to put something here which is called file if you scan a few types and just do some guesswork you will come across this class called HTTP posted file and you would think obviously that this is the type I need to use here but this is a sealed class with a non public constructor so the default mortal binder cannot create an instance of this class so even though it is actually a good candidate that map's well to the file control on the client side and can be bound manually if you write some code but the default model binder will not bind this your file control to this class because it cannot instantiate it so a better class to use is a public class with a public constructor it's a base class called file HTTP posted file base that's what the default model binder will automatically bind your files to because this is the wrong type so that's one mistake you want to take care of there's our same UI now I'll just open index dot HTML and O'Henry select these two files and I click upload and I get the error why is that because this is null so if I change this to HTTP file base that'll bind the default mode of bind mortal binder will then bind that control to this now let me set a breakpoint I'll select a few files and select all of these files for files selected and if we break here we see that there's something over here it does have something now it has only one file and that's the next problem I uploaded for files but I have only the first file that is because every file you upload is bound to one instance of HTTP posted file base since you uploaded many files you want to have some kind of a collection here either an array or an ienumerable of it anything it'll bind to anything as long as it's a collection you could do this and it'll bind see I have two files now the same information that wasn't the client for each file I have it over here or I could even have an array I could have an eye list I could have an array I could have an eye collection could have higher order collection types also it will bind to all of them but the baser it is the better it is generally for polymorphism now the next thing is this is many files and the name doesn't indicate that so I'd like to make this plural now if I've made this argument plural I need to go back and change the control controls name also to the same name otherwise the mortal binder will not bind it and even then this is a better name that's more indicative of the plurality of the contents of this control rather than simply file that's the other thing you need to take care of I recently had a stack overflow question which I also posted an answer to and that's the question in which I had a file input type and a submit button just like our scenario and has had an enclosed type of form data and a method of post and on the server I had just an HTTP POST avail erroneously had taken this and it wasn't binding to this and I discovered what the reason was which I told you that you need HTTP posted file base and you need some kind of a collection of that so feel free to read this answer I will post a link to this in the description for this video now on the server you can do different things with it you can basically save for each file you can save there's a function called save as you can give it a part that I think is a path on the physical drive on the server so it's not a virtual path it's a physical path and you can get a physical path using the server dot map path function I'm not going to do all of that my focus here is how to use the file control and so this should be good enough for us if we get something over here then that should be good enough I'll display how many files we've uploaded to the server let's just run this much I'll select two files and upload them to the server and we get the message from the server two files uploaded let's look at the network tab to see what we actually sent to the server and reload this control and we made a request to the upload action and this time you will see that we actually sent each of the files separated by this boundary here is a boundary this is some metadata about the file the first file is Owen Reed or JPEG that's the file contents serialized as a string that's the second file you can check that by selecting a text file let's select this file upload it and if I see the baram's I'll see that I have a boundary metadata about the file contents of the file and then the boundary again another attribute of the file element is accept which allows you to filter the kinds of files you can select let me demonstrate that let's say we want the user to be able to select only image files so I can come here and say accept and pass in a comma-separated list of either mime types like image dot PNG is a mined type comma image dot jpg is a mime type if I'm not sure of whether this is jpg or jpg or MPEG what's the correct mime type I can just say image dot star and that will allow me to select all kinds of images this time I'm only able to select image files this dialog has a file filter and it shows me only the image files now mind you that attribute only controls the visual display for this dialogue it doesn't actually hinder me from selecting a file different from the filter I specified I still need some code on both the client and the server to be able to hedge against that but for what it's worth you get this nice filter also this filter is not consistent across all browsers if you were to run this on different browsers you would get different results if I are on the rasaan edge I might see the same result for image files no look I get a different visual display ie will also give me something completely different look ie gives me this kind of a thing that includes HTML and stuff so all browsers have implemented everything differently you got to check every piece of quarry right on every damn browser before you actually commit it that's how crazy it has gotten these days anyway moving on and one event I'd like to tell you about is called the change event on the file input element and that happens when you change the selection of files let's say I select file O'Henry that would have affected both the value property and the files property files property would have just one file right if I select something else even if I select the same file again but also select other files that triggers a change event because the selection of the files has changed so the value property may or may not have changed because the value property displays just the first file you selected but the files property will have changed now it has two files now how can we use this change event any which way you want whatever you want to do if they use a celexa file maybe you want to preview the images I can show you an example I have so I select files and I preview them the change event now I'm not going to do this right now but let's just use the change event in this example what we will do is we will select jQuery I will define for this file input control and what we're going to do in this change event is just display in a list the names of the files that have been selected so I'll create a list out of this let's say an ordered list and I won't put any contents here in the change event what I'm gonna do is if event the files will be in the event target dot files because the event target is going to resolve to the file input control and the files property on that has the files so I'm saying if there are any files and first remove everything from the list if it had previous items maybe you made a selection remove all the previous items from the list so I'm gonna say from this list remove all the children and then for each of the files remember you cannot do as I said earlier you cannot do files dot for each because it is not an array you can do a ray dot from and then for each or better yet just user do not use a four in loop because that's only for enumerable properties use a for off loop I'll get each file and then for each file I'll just add an li and that L I will have the name of the file that's it and I'll add this Li to the list that's about it now I can select both of these files and I have them on the list if I select different files these ten files then I see this and we can even upload them on the server I hope you enjoyed this video and learned something new there was one thing I forgot to mention if I removed any JavaScript code that I had and simply had the HTML markup only the control out of the box still would allow me to drag and drop files on it here I have a few files I'm gonna select some image files are these and drag and drop them on the control since I have removed the JavaScript we do not see the list below but the control still selects these [Music] this can be verified by checking the files property on the control do you want to start a career as a software developer maybe you already are a software developer but you're just a beginner with one to four years of experience and you don't quite understand what's going on you need some help you need a helping hand pull you up teach you stuff that you ought to have learned while you were in college but you didn't get the chance to learn if you don't have good teachers then maybe even have the time then or maybe you're someone who's not a software developer you're a hairstylist a mechanical engineer maybe you work at a retail store arranging clothes and doing all those chores and you want to make a better career for yourself then I have of course I will be starting online which you can attend from your home it's not a bunch of videos you have to watch it will be me actually teaching you every other day or so for a couple of hours every week over a long long period of time I'll be holding your hand I'll be teaching you everything from scratch assuming you don't know anything about anything and by the end of the course I'm pretty confident you will if you got the aptitude which I'll help you with it in mind before you start the course so I don't want you to take the course if you don't have the amateurs but you have the aptitude and you put them the hard work I guarantee you'll go a long way I guarantee that you've been very successful as a software please go to my website sub th dotnet scroll to the bottom for now and join the mailing list please remember I do not spam anyone I do not send any foolish emails about anything else and I don't need to sell your email to anyone I don't even know who said it to I and if I knew I wouldn't sell it to anyone so there's no apprehension you should have about those things I'm just a regular plain old guy just like you and trying to make a living [Music] [Applause] [Music] [Applause] [Music] [Applause] [Music] [Applause] son [Applause] [Music] [Applause] [Music] the world you encounter is full of boundaries they appear to surround all objects they delineate your body and define its shape they form the surfaces and edges of everything within your view they mark the extent of your yard the edge of your town or city the dimension of your country and many even more subtle delineations and yet boundaries are the most illusory of realities of parent aspects while very useful to make sense of the world essential indeed the impression boundaries give is that things are isolated entities that impression that basic assumption that each object is a unit unto itself separate from all that surrounds it that impression is extremely deceiving in a very significant way here in volume 5 we've been looking at words and ideas exploring how a word and the idea behind it differ from the real nature of things the notion of borders of boundaries of a surface confining any object lines delineating open spaces define markers imposing time on a flowing now moment all these imply and essence of things that is not really there [Music] [Music] imagine psychologists where the human beings are all creatures with special needs and I think one of our special needs is for meaning our lives were not meant to be just lived for the daily sake of physical existence now that meaning in a tribal setting is automatically provided for you because you're bigger than yourself and you belong to something greater than you state and when you're connected with nature you're connected with some spiritual practice or I believe yes I mean transcends your daily struggles for survival of in society SPH we do stuff like we talk about meaning a lot when we talk about broad values such as freedom and democracy and so on but that's not what people experience in their daily lives nobody experiences democracy in our lives mostly people work in institutions were told what to do and they have no voice on a matter whatsoever and the freedom is really used to making choices review meaningless alternatives so there's a deep and the end is more more disconnection as we already mentioned so there's there's a deep lack of meaning people's life the addictions can actually send come along and provide a false temporary but momentary satisfactory sense of meaning and meaning is important to all of us we all want to feel there's something more significant about our lives than simply the fact that we have dinner and evening defecated [Music] [Music] you
Info
Channel: Sathyaish Chakravarthy
Views: 27,531
Rating: undefined out of 5
Keywords:
Id: yzAyKdtw4pg
Channel Id: undefined
Length: 37min 7sec (2227 seconds)
Published: Wed Jul 31 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.