简体   繁体   中英

Javascript get Blob with Uint8Array

i'm trying to receive data from websocket using JS and VUE and i have problem:

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:

 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)

shows:

Blob {size: 187086, type: ""}

but it should be:

ArrayBuffer(187086)

and because of it type is undefined.

But i have other (clear js version) not VUE and there it works fine.

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. Note that arrayBuffer returns a promise ; reading the blob content is an asynchronous operation.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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