【问题标题】:Javascript get Blob with Uint8ArrayJavascript 使用 Uint8Array 获取 Blob
【发布时间】:2021-04-23 11:41:34
【问题描述】:

我正在尝试使用 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,它工作正常。

你能帮我吗,怎么了?

【问题讨论】:

  • 在您的代码中,您混合了this.msgmsg。它是哪一个?此外,代码中似乎有几个从未声明过的变量。
  • "和 console.log('!!!BYTE', bytes) 显示:Blob {size: 187086, type: ""}" 恕我直言,我觉得这很难相信。 new Uint8Array 的返回值是 never Blob

标签: javascript vue.js websocket


【解决方案1】:

假设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...
    });
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
  • 2018-09-08
  • 2021-03-16
  • 2012-12-29
  • 2010-11-05
  • 2017-09-15
  • 1970-01-01
相关资源
最近更新 更多