JAVASCRIPT
Uploading Files to an API Using JavaScript FormData
Learn to send files, images, or documents to a REST API endpoint from your web browser or Node.js application using the FormData object and Fetch API.
async function uploadFileToAPI(fileInputId, apiUrl, additionalData = {}) {
const fileInput = document.getElementById(fileInputId);
if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
throw new Error('No file selected for upload.');
}
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file, file.name); // 'file' is the field name expected by the API
// Append any additional data fields
for (const key in additionalData) {
formData.append(key, additionalData[key]);
}
try {
const response = await fetch(apiUrl, {
method: 'POST',
body: formData
// Note: 'Content-Type' header is automatically set to 'multipart/form-data'
// with the correct boundary when sending FormData, so don't set it manually.
});
if (!response.ok) {
const errorDetail = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(`File upload failed: ${response.status} - ${JSON.stringify(errorDetail)}`);
}
const result = await response.json();
console.log('File uploaded successfully:', result);
return result;
} catch (error) {
console.error('Error during file upload:', error.message);
throw error;
}
}
// Example HTML (not part of JSON, just for context):
// <input type="file" id="myFileInput"/>
// <button onclick="uploadFileToAPI('myFileInput', 'https://api.example.com/upload', { userId: 123 })">Upload</button>
// Example usage (assuming an HTML file input exists):
// (async () => {
// try {
// // To run this example, you would need an HTML input:
// // <input type="file" id="exampleFileInput" />
// // Then, simulate a file selection or run in a browser.
// // If running in Node.js, you'd need to create a Blob or File object.
// // const dummyFile = new Blob(['Hello, World!'], { type: 'text/plain' });
// // dummyFile.name = 'hello.txt';
// // // Then you would need to manually construct FormData with this:
// // const nodeFormData = new FormData();
// // nodeFormData.append('file', dummyFile, dummyFile.name);
// // const result = await uploadFileToAPIWithFormData(nodeFormData, 'https://api.example.com/upload');
// // console.log(result);
// } catch (e) {
// console.error('File upload operation failed:', e);
// }
// })();
How it works: This JavaScript snippet demonstrates how to upload files to a REST API using the `FormData` object and the Fetch API. `FormData` allows you to construct a set of key/value pairs representing form fields and their values, including binary file data. When passed as the `body` of a `fetch` request, the browser automatically sets the `Content-Type` header to `multipart/form-data`, which is the standard way to send files to a server. It also includes error handling for failed uploads.