NodeJS: sending/uploading a local file to a remote server

After gazillion of trial-failure this worked for me. Using FormData with node-fetch. Oh, and request deprecated two days ago, btw.

const FormData = require('form-data');
const fetch = require('node-fetch');

function uploadImage(imageBuffer) {
  const form = new FormData();
  form.append('file', imageBuffer, {
    contentType: 'image/jpeg',
    filename: 'dummy.jpg',
  });
  return fetch(`myserver.cz/upload`, { method: 'POST', body: form })
};

In place of imageBuffer there can be numerous things. I had a buffer containing the image, but you can also pass the result of fs.createReadStream('/foo/bar.jpg') to upload a file from drive.

Leave a Comment