问题
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:
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
.
回答2:
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
})
来源:https://stackoverflow.com/questions/48291288/how-to-send-array-buffer-data-along-with-string-json-to-nodejs-server