Search code examples
node.jshttpbuffermulter

Store custom image http call with Multer in NodeJS


I have HTTP call with Buffer image inside from NodeJS Server 1 (run at localhost:5000) to NodeJS Server 2 (run at localhost:5001)

There are the Server 1 axios call:

await axios.post('http://localhost:5001/', {
  buffer: fileBuffer,
  ...otherData //
})

I read that Multer gets the image from req.files, but in my case they arrive as req.body.buffer

How can i do?


Solution

  • Solved
    I haven't used Multer

    On Server 2 use Buffer.from() for get Buffer from your http call (because is an JSON array) and then fs.writeFile() or fs.writeFileSync() write file on disk

    This is the way I used (Server 1):

    await axios.post('http://localhost:5001/', {
      buffer: fileBuffer,
      name: fileName
    })
    

    Server 2:

    const { body } = req // This is the HTTP object, it contains buffer and name
    const data = Buffer.from(body.buffer) // Transform array to buffer value
    const path = './public/' + body.name // "./public/sample.jpg"
    
    fs.writeFileSync(path, data) // writeFile and writeFileSync also accept Buffer