10

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?

1
  • JSON.parse/JSON.stringify should work on typed arrays just fine. Commented Jan 16, 2018 at 23:16

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

1

If you work with express.js you can use multer

From their docs:

var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.