JAVASCRIPT
Uploading Files to API with FormData (JavaScript)
Upload files efficiently to a web API from the browser using JavaScript's Fetch API and FormData, handling 'multipart/form-data' content type.
<input type="file" id="fileInput" multiple>
<button id="uploadButton">Upload Files</button>
<pre id="responseOutput"></pre>
<script>
const fileInput = document.getElementById('fileInput');
const uploadButton = document.getElementById('uploadButton');
const responseOutput = document.getElementById('responseOutput');
const UPLOAD_API_URL = 'https://api.example.com/upload'; // Replace with your actual upload API endpoint
uploadButton.addEventListener('click', async () => {
const files = fileInput.files;
if (files.length === 0) {
alert('Please select at least one file to upload.');
return;
}
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
formData.append('files[]', files[i]); // 'files[]' is a common name for multiple files
}
try {
responseOutput.textContent = 'Uploading...';
const response = await fetch(UPLOAD_API_URL, {
method: 'POST',
// No 'Content-Type' header is needed when using FormData, as fetch will set it
// automatically to 'multipart/form-data' with the correct boundary.
body: formData
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! Status: ${response.status}, Details: ${errorText}`);
}
const result = await response.json();
responseOutput.textContent = 'Upload Successful:
' + JSON.stringify(result, null, 2);
} catch (error) {
console.error('Upload failed:', error);
responseOutput.textContent = 'Upload Failed: ' + error.message;
}
});
</script>
How it works: This JavaScript snippet demonstrates how to upload one or more files to an API using `FormData` and the Fetch API. When a user selects files and clicks 'Upload', a `FormData` object is created. Each selected file is appended to this object. Crucially, when using `FormData` as the `body` of a `fetch` request, you should omit the `Content-Type` header; the browser automatically sets it to `multipart/form-data` with the correct boundary, which is essential for successful file uploads.