JAVASCRIPT

Performing File Uploads to REST APIs with multipart/form-data in Node.js

Send files to a REST API from your Node.js application using the `multipart/form-data` content type for robust and standard file uploads.

const fs = require('fs');
const FormData = require('form-data');
const axios = require('axios'); // Or use Node's built-in http/https or fetch with a polyfill

// --- Configuration ---
const API_UPLOAD_URL = 'http://localhost:3000/upload'; // Replace with your API endpoint
const FILE_PATH_TO_UPLOAD = './example.txt'; // Path to the file you want to upload
const FIELD_NAME_FOR_FILE = 'document'; // The name of the form field the API expects for the file
const CUSTOM_TEXT_FIELD = 'description'; // An optional additional text field
const CUSTOM_TEXT_VALUE = 'This is a test document upload.';

// --- Create a dummy file for demonstration ---
function createDummyFile(path) {
  if (!fs.existsSync(path)) {
    fs.writeFileSync(path, 'This is the content of the example file.');
    console.log(`Created dummy file: ${path}`);
  }
}
createDummyFile(FILE_PATH_TO_UPLOAD);

async function uploadFileToApi() {
  if (!fs.existsSync(FILE_PATH_TO_UPLOAD)) {
    console.error(`Error: File not found at ${FILE_PATH_TO_UPLOAD}`);
    return;
  }

  const form = new FormData();

  // Append the file
  form.append(FIELD_NAME_FOR_FILE, fs.createReadStream(FILE_PATH_TO_UPLOAD));

  // Append other text fields if needed
  form.append(CUSTOM_TEXT_FIELD, CUSTOM_TEXT_VALUE);
  form.append('userId', '123');

  try {
    console.log('Attempting to upload file...');
    const response = await axios.post(API_UPLOAD_URL, form, {
      headers: {
        ...form.getHeaders(), // Important: getHeaders sets the Content-Type with boundary
        'Authorization': 'Bearer YOUR_API_TOKEN' // If your API requires authentication
      },
      maxBodyLength: Infinity, // For potentially large files
      maxContentLength: Infinity // For potentially large files
    });

    console.log('File upload successful!');
    console.log('Status:', response.status);
    console.log('Response data:', response.data);
  } catch (error) {
    if (error.response) {
      console.error('File upload failed with response:', error.response.status, error.response.data);
    } else if (error.request) {
      console.error('File upload failed, no response received:', error.request);
    } else {
      console.error('File upload failed with error:', error.message);
    }
  }
}

uploadFileToApi();
How it works: This Node.js snippet demonstrates how to upload files to a REST API using the `multipart/form-data` content type. It leverages the `form-data` library to construct the multipart request body, which can include both files (using `fs.createReadStream`) and other text fields. `axios` is used for making the HTTP POST request, with crucial `form.getHeaders()` integration to correctly set the `Content-Type` header, including the boundary string. This method is standard for handling file uploads across various web APIs and ensures proper data encoding for both binary and text parts.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs