JAVASCRIPT
Client-Side API File Upload with FormData
Learn to upload files to an API endpoint from the client-side using JavaScript's Fetch API and the FormData object, essential for handling user-submitted media and documents.
<!-- HTML input element -->
<input type="file" id="fileInput" accept="image/*">
<button id="uploadButton">Upload File</button>
<script>
document.getElementById('uploadButton').addEventListener('click', async () => {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (!file) {
alert('Please select a file first.');
return;
}
const API_UPLOAD_URL = 'https://api.your-service.com/upload';
const formData = new FormData();
formData.append('file', file); // 'file' is the name of the form field expected by the API
formData.append('description', 'User uploaded image'); // Add other fields if needed
try {
const response = await fetch(API_UPLOAD_URL, {
method: 'POST',
// When using FormData, the 'Content-Type' header is automatically set
// to 'multipart/form-data' with the correct boundary by the browser.
// Do NOT manually set 'Content-Type' when sending FormData.
body: formData
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`Upload failed: ${response.status} ${response.statusText} - ${JSON.stringify(errorData)}`);
}
const result = await response.json();
console.log('File uploaded successfully:', result);
alert('File uploaded successfully!');
} catch (error) {
console.error('Error uploading file:', error);
alert(`Error uploading file: ${error.message}`);
}
});
</script>
How it works: This snippet demonstrates how to perform a client-side file upload to an API endpoint using JavaScript's `FormData` object and the `fetch` API. After a user selects a file, a `FormData` instance is created, and the file (along with any other required form fields) is appended to it. The `fetch` request then sends this `formData` as the body. It's crucial not to manually set the `Content-Type` header when using `FormData`, as the browser handles setting it to `multipart/form-data` with the correct boundary automatically.