0

I have 2 nodeJS services and I would want to upload file in a dir, from one NodeJS (backend) to another NodeJS(backend). The receiver nodeJS is an express app.

Looking for some working code sample.

PS: Couldn't find any code samples in search, since everywhere it was Multer from client to server uploads that receives multipart/form-data.

Kaushik
  • 1,271
  • 2
  • 18
  • 35
  • Since you need to use ``multer`` anyways, I think you could take a few of those client to server uploads and convert it to server to server. The concept's definitely the same. – Take-Some-Bytes Aug 21 '20 at 03:33
  • this is a video tutorial with complete code example uploaded on github: it shows how to upload binary files using multer: https://www.youtube.com/watch?v=d8COHTGz2cc don't forget to subscribe – Inzamam Malik Oct 20 '22 at 09:23

1 Answers1

0

Uploading file using POST request in Node.js

Receive the file first as you correctly said using Multer. Then, you may either save the file to a temporary directory before uploading it again or just send the file as-is.

You need to setup a server running with Multer on the 2nd server that wishes to receive the file.

const express = require('express');
const app = express();
const upload = multer({ dest: 'files/' });
app.post('/upload', upload.single('file'), (req, res) => {
    res.sendStatus(200);
});
app.listen(3001);

Then on the server you wish to send the file from, do something like this:

const request = require('request');
const req = request.post('localhost:3001/upload', (err, res, body) => {
  if (err) throw new Error(err);
  if (res && res.statusCode == 200) {
    console.log('Success');
  } else {
    console.log('Error');
  };
});
const form = req.form();
form.append('file', fs.createReadStream('./location/to/file'));
PiggyPlex
  • 631
  • 1
  • 4
  • 15