JAVASCRIPT
Upload a File to an API using FormData in JavaScript
Learn to securely upload files to an API endpoint from a web client using JavaScript's `FormData` object and the `fetch` API, perfect for image or document uploads.
<!-- HTML part for demonstration -->
<input type="file" id="fileInput" accept="image/*,application/pdf">
<button id="uploadButton">Upload File</button>
<script>
async function uploadFile(file, url, apiKey) {
const formData = new FormData();
formData.append('file', file); // 'file' is the field name expected by the API
// You can append other form fields too:
// formData.append('userId', '123');
try {
const response = await fetch(url, {
method: 'POST',
headers: {
// DO NOT set Content-Type header when sending FormData; fetch sets it automatically
'Authorization': `Bearer ${apiKey}`
},
body: formData
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP error! Status: ${response.status}, Message: ${errorText}`);
}
const result = await response.json();
console.log('File uploaded successfully:', result);
return result;
} catch (error) {
console.error('Error uploading file:', error);
throw error;
}
}
// Example usage:
document.getElementById('uploadButton').addEventListener('click', async () => {
const fileInput = document.getElementById('fileInput');
if (fileInput.files.length > 0) {
const selectedFile = fileInput.files[0];
const API_UPLOAD_URL = 'https://api.example.com/upload';
const MY_API_KEY = 'your_secret_api_key';
try {
await uploadFile(selectedFile, API_UPLOAD_URL, MY_API_KEY);
alert('File upload initiated!');
} catch (error) {
alert('File upload failed: ' + error.message);
}
} else {
alert('Please select a file first.');
}
});
</script>
How it works: This snippet demonstrates how to upload a file to an API using JavaScript's `FormData` object. It takes a file selected by the user from an `<input type="file">` element and appends it to a `FormData` instance. This `FormData` object is then used as the `body` for a `fetch` POST request. It's crucial not to manually set the `Content-Type` header when using `FormData`, as `fetch` automatically sets it to `multipart/form-data` with the correct boundary. Authentication headers like `Authorization` can be added as usual. The snippet includes basic error handling and an example HTML setup.