[英]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.