Javascript 使用 Uint8Array 获取 Blob

Javascript get Blob with Uint8Array

我正在尝试使用 JS 和 VUE 从 websocket 接收数据,但我遇到了问题:

要接收数据,我正在使用代码:

created() {
console.log('Starting Connection to WebSocket')
this.connection = new WebSocket('ws://127.0.0.1:8080/live')
// this.connection = new WebSocket('ws://echo.websocket.org')
this.connection.onopen = function (event) {
  console.log(event)
  console.log('Success')
}
this.connection.onmessage = webSocketOnMSG
 },

并尝试解析 blob:

 function webSocketOnMSG(msg) {
  if (typeof (msg.data) === 'string') {
    jsonMSG(msg.data)
    return
  }
  bytes = new Uint8Array(msg.data)
  console.log('!!!BYTE', bytes)
  type = bytes[0]
  switch (type) {

  }
}

console.log('!!!BYTE', bytes)

显示:

Blob {size: 187086, type: ""}

但应该是:

ArrayBuffer(187086)

因此 type 未定义。

但是我有其他的(清晰的js版本)不是VUE并且在那里工作正常。

你能帮帮我吗,怎么了?

假设 msg.data 确实是一个 blob,您将使用 blob 的 arrayBuffer 方法将该 blob 读入 ArrayBuffer,然后从 Uint8Array那个缓冲区。请注意 arrayBuffer returns 一个 promise;读取 blob 内容是一个异步操作。

示例:

function webSocketOnMSG(msg) {
    if (typeof msg.data === "string") { // `typeof` isn't a function, no need for `()`
        jsonMSG(msg.data);
        return;
    }
    // Assuming `msg.data` really is a `Blob`, then:
    msg.data.arrayBuffer()
    .then(buf => new Uint8Array(buf))
    .then(bytes => {
        console.log('!!!BYTE', bytes);
        const type = bytes[0];
        switch (type) {
            // ...
        }
    })
    .catch(error => {
        // ...handle/report error...
    });
}