Learn how to upload files to a server using the Fetch API in a simple and straightforward way.
Uploading files to a server can sometimes be a challenging task that requires hours of research. In this tutorial, I will guide you on how to upload files using the Fetch API.
To begin, let’s assume you have a form with a file input field:
<input type="file" id="fileUpload" />
To handle the file upload, we’ll attach a change
event handler to the file input field:
document.querySelector('#fileUpload').addEventListener('change', event => {
handleImageUpload(event);
});
The main logic for handling the file upload will be encapsulated within the handleImageUpload()
function:
const handleImageUpload = event => {
const files = event.target.files;
const formData = new FormData();
formData.append('myFile', files[0]);
fetch('/saveImage', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
};
In the example above, we perform a POST request to the /saveImage
endpoint. We create a new FormData
object and assign it to the formData
variable. Then, we append the uploaded file to the FormData object using the append()
method. If you have multiple file input elements, you can use multiple append()
calls.
The data
variable within the second then()
block will contain the parsed JSON response data. It is assumed that your server will provide a JSON response.
For guidance on handling images uploaded server-side, refer to the how to handle file uploads with Node.js tutorial.