将Uint8Array从浏览器传输到节点

时间:2017-01-27 22:46:25

标签: javascript node.js typed-arrays

我有一个Uint8Array包含我需要发送到节点服务器进行处理的原始像素数据(RGBA)。我将它转换为浏览器上的blob并通过ajex发送,但检索节点端的数据是有问题的。我可以将{blob}作为Bufferreq.files.image.data但是如何将其转换回与Uint8Array相同的序列?

在浏览器上:

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
    })
  })
}

在节点服务器上:

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

这抱怨Buffer size does not match width and height req.files.image.data是blob而不是Uint8Array

2 个答案:

答案 0 :(得分:0)

根据发布的数据创建

Uint8Array

答案 1 :(得分:0)

原来问题在于我是如何创建blob的。我传递了一个TypedArray,blob只知道如何存储TypedArrays数组。所以它将我的数据转换为字符串,然后将其存储在blob中。

解决方案是简单地将TypedArray包装在一个数组中。

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