// Get the file input element
const fileInput = document.querySelector('#file-input');
// Add an event listener for the 'change' event on the file input
fileInput.addEventListener('change', (event) => {
// Get the selected file
const file = event.target.files[0];
// Create a FormData object and append the file to it
const formData = new FormData();
formData.append('file', file);
// Use the Fetch API to send a POST request with the file data
fetch('/upload', { method: 'POST', body: formData });
});
code
JavaScript File Upload using Fetch API and FormData
This JavaScript code demonstrates handling file upload using the Fetch API and FormData. It listens for changes in a file input element, retrieves the selected file, appends it to a FormData object, and sends a POST request to the '/upload' endpoint. The comments provide explanations for each part of the code.
Fetch API
File Upload
FormData