简体   繁体   中英

Transfer Uint8Array from browser to node

I have a Uint8Array containing raw pixel data (RGBA) I need to send to my node server for processing. I convert it to a blob on the browser and send that through ajex, but retrieving the data on the node side is being problematic. I can get the blob as a Buffer through req.files.image.data but how do I convert that back in to the same sequence I had with the Uint8Array ?

On the browser:

sendBlob(new Blob(data, {type: "application/octet-stream"}), ...)

function sendBlob (blob, name) {
  return new Promise((resolve, reject) => {
    let data = new FormData()
    data.append('image', blob, name)
    data.append('width', 640)
    data.append('height', 427)
    $.ajax({
       url: '/upload',
       type: 'POST',
       data: data,
       processData: false,
       contentType: false,
       error: reject,
       success: resolve
    })
  })
}

On node server:

lwip.open(req.files.image.data, {
  width: parseInt(req.body.width),
  height: parseInt(req.body.height)
}, (image, err) => ...)

This complains Buffer size does not match width and height as req.files.image.data is the blob not the wrapped Uint8Array .

Create a Uint8Array from the posted data.

let data = new Uint8Array(req.files.image.data);
lwip.open(data, {
  width: parseInt(req.body.width),
  height: parseInt(req.body.height)
}, (image, err) => ...)

Turns out the problem was in how I was creating the blob. I passed a single TypedArray, blob only knows how to store an array of TypedArrays. So it was converting my data into a string before storing it in the blob.

The solution is to simply wrap the TypedArray in an array.

sendBlob(new Blob([data], {type: "application/octet-stream"}), ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM