Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send array buffer data along with string/json to NodeJS server

I need to send image data (read as array buffer) from client page, along with additional string/json information generated by page, to NodeJS server in one request. I need both parts to be processed in one request as further image processing by server depends on that string/json sent along. What are ways to both send those by client and then parse them by server so it meets those criteria?

like image 396
okram Avatar asked Jan 16 '18 23:01

okram


1 Answers

What you are looking for is a multipart request using FormData.

FormData can be used as the body in fetch and supports Blob. An example would be this:

var binary = new Uint8Array(2)
binary[0] = 65
binary[1] = 66

var fd = new FormData()
fd.append('json_data', JSON.stringify({a: 1, b: 2}))
fd.append('binary_data', new Blob([binary.buffer]))

fetch('https://example.com/receive', {
  method: 'POST',
  body: fd
}).then(console.log)

Note: If you are using express on your server, please be warned that bodyparser does not handle multipart bodies!

Alternatives for bodyparser would be multer, connect-busboy or multiparty.

like image 181
geekonaut Avatar answered Sep 19 '22 08:09

geekonaut