简体   繁体   English

Javascript 使用 Uint8Array 获取 Blob

[英]Javascript get Blob with Uint8Array

i'm trying to receive data from websocket using JS and VUE and i have problem:我正在尝试使用 JS 和 VUE 从 websocket 接收数据,但我遇到了问题:

To receive data i'm using code:要接收数据,我正在使用代码:

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

and trying to parse blob:并尝试解析 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) {

  }
}

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

shows:显示:

Blob {size: 187086, type: ""}

but it should be:但应该是:

ArrayBuffer(187086)

and because of it type is undefined.并且因为它type是未定义的。

But i have other (clear js version) not VUE and there it works fine.但我有其他(清晰的 js 版本)不是 VUE,它工作正常。

Can you help me, whats wrong?你能帮我吗,怎么了?

Assuming msg.data really is a blob, you'd use the blob's arrayBuffer method to read that blob into an ArrayBuffer , and then make a Uint8Array from that buffer.假设msg.data确实是一个 blob,您将使用 blob 的arrayBuffer方法将该 blob 读入ArrayBuffer ,然后从该缓冲区创建一个Uint8Array Note that arrayBuffer returns a promise ;请注意, arrayBuffer返回一个promise reading the blob content is an asynchronous operation.读取 blob 内容是一个异步操作。

Example:例子:

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