Fetch API - Uploading Files



Fetch API provides a flexible way to create an HTTP request which will upload files to the server. We can use the fetch() function along with the FormData object to send single or multiple files in the request. Let us discuss this concept with the help of the following examples −

Example − Uploading a Single File

In the following program, we upload one file at a time using fetch API. Here we use the FormData object to store the file and then send it using the fetch() function to the given URL including the POST request method and the FormData object. After sending the request to the server now we use the then() function to handle the response. If we encounter an error, then that error is handled by the catch() function.




  


Output

Uploading Files

Example − Uploading Multiple Files for Single Input

In the following program, we will upload multiple files from the single input using fetch API. Here we add a "multiple" property in the tag to add multiple files. Then we use the FormData object to store multiple files and then send them using the fetch() function to the given URL including the POST request method and the FormData object. After sending the request to the server now we use the then() function to handle the response. If we encounter an error, then that error is handled by the catch() function.




     
   

Uploading Multiple files

Maximum number of files should be 2



Output

Uploading Files

Example − Uploading Multiple Files

In the following program, we will upload multiple files using fetch API. Here we select two files from the system in DOM with the attribute of file type. Then we add the input files in an array. Then we create a FormData object and append the input files to the object. Then we send them using the fetch() function to the given URL including the POST request method and the FormData object. After sending the request to the server now we use the then() function to handle the response. If we encounter an error, then that error is handled by the catch() function.




     
   

Uploading Multiple files

Output

Uploading Files

Conclusion

So this is how we can upload files to the given URL with the help of fetch() API. Here we can upload any type of file like jpg, pdf, word, etc and upload any number of files like one file at a time or multiple files at a time. Now in the next article, we will learn how the Fetch API handles responses.

Advertisements