How do I handle file uploads

Handling file uploads in JavaScript can be done using the FormData API for easy handling and XMLHttpRequest or Fetch API to send the data to the server. This ensures a smooth user experience while uploading files such as images, documents, or any other type of file.

file uploads, JavaScript, FormData, XMLHttpRequest, Fetch API, web development

<!-- HTML Form --> <form id="upload-form" enctype="multipart/form-data"> <input type="file" name="file" id="file"> <button type="submit">Upload</button> </form> <script> document.getElementById('upload-form').addEventListener('submit', function(event) { event.preventDefault(); const fileInput = document.getElementById('file'); const formData = new FormData(); formData.append('file', fileInput.files[0]); fetch('/upload', { method: 'POST', body: formData }) .then(response => { if (response.ok) { return response.json(); } throw new Error('File upload failed.'); }) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); }); </script>

file uploads JavaScript FormData XMLHttpRequest Fetch API web development