JAVASCRIPT
Upload Files to a REST API with FormData in JavaScript
Learn how to asynchronously upload files from a web form to a RESTful API endpoint using JavaScript's FormData object and Fetch API.
<!-- index.html -->
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" id="fileInput" name="myFile" multiple>
<input type="text" id="descriptionInput" name="description" placeholder="File description">
<button type="submit">Upload Files</button>
</form>
<div id="status"></div>
<script>
document.getElementById('uploadForm').addEventListener('submit', async function(event) {
event.preventDefault(); // Prevent default form submission
const fileInput = document.getElementById('fileInput');
const descriptionInput = document.getElementById('descriptionInput');
const statusDiv = document.getElementById('status');
const formData = new FormData();
formData.append('description', descriptionInput.value);
// Append each selected file
for (const file of fileInput.files) {
formData.append('files', file); // 'files' is the expected field name on the server
}
statusDiv.textContent = 'Uploading...';
try {
const response = await fetch('https://api.example.com/upload', {
method: 'POST',
body: formData // No need to set 'Content-Type', FormData handles it
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: 'Unknown error' }));
throw new Error(`Upload failed: ${response.status} ${response.statusText} - ${errorData.message}`);
}
const result = await response.json();
statusDiv.textContent = `Upload successful! ${JSON.stringify(result)}`;
console.log('Upload success:', result);
} catch (error) {
statusDiv.textContent = `Upload error: ${error.message}`;
console.error('Upload error:', error);
}
});
</script>
How it works: This snippet demonstrates how to upload files to a REST API using JavaScript's `FormData` object. An HTML form collects files and additional data. When submitted, the JavaScript captures the form data, appends selected files and text fields to a `FormData` instance, and then uses the `fetch` API to send a `POST` request to the specified API endpoint. `FormData` automatically sets the correct `Content-Type: multipart/form-data` header, simplifying file upload integration.