JAVASCRIPT
Upload File to API using FormData
Discover how to send binary file data, such as images or documents, to a REST API endpoint using the `FormData` API and `fetch` in web browsers or Node.js.
async function uploadFile(fileInputId, uploadUrl) {
const fileInput = document.getElementById(fileInputId);
const file = fileInput.files[0];
if (!file) {
console.error('No file selected.');
return;
}
const formData = new FormData();
formData.append('file', file); // 'file' is the field name expected by the server
formData.append('description', 'A user-uploaded image'); // Additional data
try {
const response = await fetch(uploadUrl, {
method: 'POST',
body: formData // No need to set Content-Type, fetch does it automatically for FormData
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`File upload failed: ${response.status} - ${errorText}`);
}
const result = await response.json();
console.log('File upload successful:', result);
return result;
} catch (error) {
console.error('Error uploading file:', error);
throw error;
}
}
// Example HTML for file input:
// <input type="file" id="myFileInput" />
// <button onclick="uploadFile('myFileInput', 'https://api.example.com/upload')">Upload</button>
How it works: This snippet illustrates how to upload a file to an API using the `FormData` interface. `FormData` provides a way to construct a set of key/value pairs representing form fields and their values, including files. When used with `fetch`, setting the `body` of the request to a `FormData` object automatically sets the `Content-Type` header to `multipart/form-data` with the correct boundary, which is essential for file uploads. You can append multiple files and other form fields to the `FormData` object before sending the request.