JAVASCRIPT
Uploading Files to API with JavaScript FormData
Efficiently upload single or multiple files to a REST API from a web browser using JavaScript's `FormData` object and the `fetch` API.
async function uploadFile(fileInputId, apiUrl) {
const fileInput = document.getElementById(fileInputId);
const files = fileInput.files;
if (files.length === 0) {
console.warn('No files selected for upload.');
return;
}
const formData = new FormData();
// Append each selected file to the FormData object
// The 'file' key here should match what your API expects
for (let i = 0; i < files.length; i++) {
formData.append('files', files[i]); // Use 'files[]' or similar for multiple
}
// You can also append other data
formData.append('userId', '123');
formData.append('description', 'User uploaded files');
try {
const response = await fetch(apiUrl, {
method: 'POST',
body: formData, // fetch API automatically sets 'Content-Type: multipart/form-data'
// No need to set 'Content-Type' header manually for FormData
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log('File upload successful:', result);
alert('Files uploaded successfully!');
} catch (error) {
console.error('Error during file upload:', error);
alert('File upload failed: ' + error.message);
}
}
// HTML Structure (for demonstration purposes, typically generated by framework)
// <input type="file" id="myFileInput" multiple>
// <button onclick="uploadFile('myFileInput', 'https://your-api-endpoint.com/upload')">Upload Files</button>
// Example Usage (assuming you have an HTML input with id="myFileInput" and a button)
// In a real application, you'd likely attach this to an event listener.
// For a quick test, you can run this in browser console after selecting files
// and replace 'https://your-api-endpoint.com/upload' with a suitable test API
// e.g., a simple Node.js/Express with `multer` for multipart form data handling.
// To make this runnable without HTML setup:
if (typeof document !== 'undefined') {
const createAndAppendElement = (tag, id, type, multiple) => {
const el = document.createElement(tag);
el.id = id;
if (type) el.type = type;
if (multiple) el.multiple = true;
document.body.appendChild(el);
return el;
};
let fileInput = document.getElementById('myFileInput');
if (!fileInput) {
fileInput = createAndAppendElement('input', 'myFileInput', 'file', true);
const uploadButton = createAndAppendElement('button', 'uploadBtn');
uploadButton.textContent = 'Upload Test Files (select below)';
uploadButton.onclick = () => uploadFile('myFileInput', 'https://httpbin.org/post'); // Using httpbin for testing
}
console.log('Select files in the input field above and click the "Upload Test Files" button.');
console.log('This will use httpbin.org/post to simulate an upload.');
} else {
console.log('This file upload snippet is designed for browser environments.');
}
How it works: This JavaScript snippet demonstrates how to upload one or more files to a REST API using the `FormData` object and the `fetch` API. `FormData` provides a way to construct a set of key/value pairs representing form fields and their values, including binary file data. When `FormData` is passed as the `body` of a `fetch` request, the browser automatically sets the `Content-Type` header to `multipart/form-data`, which is the standard for file uploads. This allows for sending files along with other textual data in a single API call.