繁体   English   中英

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返回一个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...
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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