File Upload using Fetch API - JavaScript Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to this video tutorial so today what i'm going to be showing you is how you can upload a file to a server using javascript's inbuilt fetch function and what i'm going to be uploading is a user input file specified in this input of type file as well as any comments given by the user and this is going to occur when the user clicks on this button of type submit to submit the form and we're going to be handling that process in javascript but just before doing that i want to mention two important attributes that you can add to the file input element the first one is accept and with accept you can specify what type of file you will allow it to be uploaded so in this case i'm going to be uploading a jpeg image so i want to be able to upload files with a jpeg extension i can add more files more file types by entering them in a comma separated list like this so you can keep on going like that i'm just going to keep jpeg because i know that that's the only file type i'm going to be uploading and the second important option you can specify is multiple so if you include this it will allow the user to select multiple files on their system in one browse for upload so so because multiple is specified what this allows a user to do is to select more than one image at the same time and then you can upload those three files at the same time if a user selects them one by one then they're going to overwrite each other but in this example i'm only uploading one image so i'm going to remove the multiple attribute and what you'll see in most forms where there's an opportunity for multiple uploads is rather than the multiple attribute being used more than one input element is included and this can be less confusing for users in many cases because they can see how many uploads they have to make in terms of how many input elements there are on the page okay so let's move on to handling the form now the first thing i want to do in javascript is to get the form by its id and i'm going to attach an event listener to the form i'm listening out for a submit on the button and when that occurs there's going to be a handler function and inside this handler function i'm going to handle the submit of the form the first thing i want to do is to prevent the default behavior html wants to send the form itself which will refresh the page i need to prevent this behavior so that i can handle it here in javascript okay so the next thing i'm going to want to do is to select the file that the user wants to upload so i'm going to select the file input element by its id which is file and to access the actual file i access the files object on this element and this stores the files that the user has selected in a list so it's going to be in list format even if the user has only selected one file so i can always access one file at position zero and i'm going to save a reference to that file in a variable and the other data that i want to post is the comments so i need to select the input element for that as well and this time it's not a file i want to access the value of that input element and i'll reference that in a variable too okay so now that i've selected the data that i want to send i'm going to create a new instance of a special inbuilt object in javascript and that is the form data object and there's two reasons that i'm doing this so the first one is that the data that i've already selected i can store it very easily in key value pairs within a form data object and the second is that a form data object simplifies my post request i won't have to specify any headers any encoding anything like that the browser will automatically set all of those for me if i store my data inside of a form data object so in general it's a nice way to send form data with javascript so what i'm doing here already is creating a new form data object by using the new keyword before form data but what i still need to do is to save a reference to the object that i'm creating so a lot of people call this form data so i will stick to this naming convention here but you can call it anything you like now what i need to do is to store the data that i've selected inside this new object and the way that i do that is by calling the append method on the object and then i enter a key under which i want to store a bit of data so first i'm going to store the user file so i'll give it a key of user file in the second argument position i need to pass in the data so that is user file and optionally in the third position for a file i can specify a new name for the file so for example i could call it user file dot jpeg and then it would be saved under this file name rather than the file name that the user has given to it like in this example 1.jpg and for the comments it's the same format except there's no optional third argument so i can give this data a key so i'll save it under user comments and then i pass in the data in the second position so now that i've stored my data inside my form data object i'm ready to make the post request with fetch so i start by calling fetch and i need to enter an endpoint for this post request so in this case i'm going to use the test endpoint provided by http bin and that is forward slash post and in the second argument position i need to enter an object so to specify the type of request i need to create a property called method and inside there i specify the type so in this case it's post and then the body of this request is going to be the form data object so because i'm using a form data object i don't actually need to specify anything else for this post request the browser is going to take care of setting the necessary headers for me and in fact if you try setting the content type property for this post request it can lead to an error so it's best to let the browser do its thing and take care of that for you so fetch returns a promise and you can handle the result of a promise using special then syntax and you have available to you the result as a parameter and then in a handler function you can do something with that so in this case first of all what i need to do is to convert the response from json to a javascript object and then in the next then statement i have the data available to me and i'll log that to the console and if there's an error it's going to fire the catch statement and all i'm going to do here is log the error to the console if there is one okay so that's it hopefully everything is working now let's test it out in the browser okay so i'm going to select a file to upload and write some comments now when i click upload file this will make the post request and this is the response from the server so let's have a look and see what it contains so remember that this server sends back to me my request so let's see what headers were set in my request so importantly the content type was specified for me as multi-part form data and the encoding was also set to so i didn't set any of these headers but the browser has taken care of that for me now in terms of data we have inside this files property the user file so this is the jpeg that i sent and also in the form property we have the user comments and you can see that they are saved under the keys that i gave to them in javascript so that is how you can post a file to a server using the inbuilt fetch function so that is it for this tutorial i hope you found it useful if you did please consider hitting the like button down below this video and if you'd like to see more content like this don't forget to subscribe to the channel
Info
Channel: OpenJavaScript
Views: 26,046
Rating: undefined out of 5
Keywords:
Id: e13T3O0Iyvc
Channel Id: undefined
Length: 9min 1sec (541 seconds)
Published: Fri Jun 10 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.