JAVASCRIPT
Uploading Files to an API with Node.js and FormData
Discover how to programmatically send multipart/form-data, including file uploads, to a REST API using Node.js, the `axios` library, and `form-data` for stream handling.
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');
async function uploadFileToAPI(apiEndpoint, filePath, fileName, additionalFields = {}) {
try {
const form = new FormData();
// Append the file stream
const fileStream = fs.createReadStream(filePath);
form.append('file', fileStream, { filename: fileName }); // 'file' is the field name on the API side
// Append additional fields
for (const key in additionalFields) {
form.append(key, additionalFields[key]);
}
const response = await axios.post(apiEndpoint, form, {
headers: {
...form.getHeaders(),
// Add any other necessary headers, e.g., Authorization
// 'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
},
maxBodyLength: Infinity, // Important for large files
maxContentLength: Infinity, // Important for large files
});
console.log('File upload successful:', response.data);
return response.data;
} catch (error) {
console.error('File upload failed:', error.response ? error.response.data : error.message);
throw error;
}
}
// Example Usage:
// const fileToUpload = path.join(__dirname, 'my-document.pdf');
// const apiEndpoint = 'https://api.example.com/upload';
// uploadFileToAPI(fileToUpload, 'document.pdf', apiEndpoint, { description: 'Important document' })
// .then(data => console.log('API response:', data))
// .catch(err => console.error('Upload error:', err));
How it works: This Node.js snippet demonstrates how to send files to an API using multipart/form-data. It leverages the `form-data` library to build the request body, allowing files to be streamed directly from the file system. `axios` is used to send the POST request, with important headers automatically generated by `form-data` for correct content type negotiation.