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>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?