Skip to content
This repository has been archived by the owner on Nov 21, 2024. It is now read-only.

Latest commit

 

History

History

04-WebBinaryApi

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

网页二进制接口

相关文档可以大概预览一下,不需要刻意记住。

获取二进制数据

网页不像Nodejs,可以接触到二进制数据的情况并不多,简单概括下几种情况。

Ajax

let xhr = new XMLHttpRequest();
xhr.open("GET", someUrl);
xhr.responseType = "arraybuffer";
xhr.onload = function() {
  let uint8 = new Uint8Array(xhr.response);
  console.log(uint8);
};
xhr.send();

Fetch

fetch(someUrl)
  .then(function(response) {
    return response.arrayBuffer();
  })
  .then(function(arrayBuffer) {
    let uint8 = new Uint8Array(arrayBuffer);
    console.log(uint8);
  });

Websocket

let socket = new WebSocket(someUrl);
socket.binaryType = "arraybuffer";
socket.onmessage = function(e) {
  let uint8 = new Uint8Array(e.data);
  console.log(uint8);
};
socket.send();

Canvas

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const uint8ClampedArray = imageData.data;

FileReader

const fileInput = document.getElementById("fileInput");
const file = fileInput.files[0];
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function() {
  let uint8 = new Uint8Array(reader.result);
  console.log(uint8);
};