how to upload file saved in memory by multer to another API

I've stumbled upon the same issue and here is what I've managed to come up with.

First of all I used the form-data package to mimic the FormData data structure on the server side and here is the util file that does that.

    const FormData = require('form-data')
    const formData = new FormData()
    const config = {
       headers: {
         'Content-Type': `multipart/form-data; boundary=${formData.getBoundary()}`
       }
    }
    export default { data: formData, config }

and here is my node.js api file


import formSet from '../utils/formData'

const multer = require('multer')
const upload = multer()

const { Router } = require('express')
const router = Router()

......

router.post('/api/images', upload.single('image'), async (req, res) => {
  formSet.data.append('image', req.file.buffer, { filename: req.file.originalname })
  formSet.data.append('other_data', 'value')
  const response = await axios.post('/images', formSet.data, formSet.config)

  .......

})

The team was able to get through this by converting the buffer to Stream first and send form data differently.

import stream from 'stream';
import rq from 'request-promise';

const { Duplex } = stream;

function bufferToStream(buffer) {
  const duplexStream = new Duplex();
  duplexStream.push(buffer);
  duplexStream.push(null);
  return duplexStream;
}

async function store({
  originalname, mimetype, size, buffer,
}) {
  logger.debug(`Saving image name:${originalname} type:${mimetype} size:${size}`);

  const formData = {
    image: {
      value: bufferToStream(buffer),
      options: {
        filename: originalname,
        contentType: mimetype,
        knownLength: size,
      },
    },
  };

  const options = Object.assign({}, IMAGE_SAVE_ENDPOINT, { formData });
  const response = await rq(options);
  return response.id;
}

Using Request, formdata should be set to the buffer:

formData: { image: req.file.buffer }