javascript Sending and Receiving Binary Data

為了增加傳輸的速度, 所以要把沒被壓縮的大檔案在server side 壓縮後, 在用戶端解壓縮, 就需要處理 binary data.

由於我是用 fetch 來做 get/post, 所以會使用到 arraybuffer, 使用範例:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

const req = new XMLHttpRequest();
req.open("GET", "/myfile.png", true);
req.responseType = "arraybuffer";

req.onload = (event) => {
  const arrayBuffer = req.response; // Note: not req.responseText
  if (arrayBuffer) {
    const byteArray = new Uint8Array(arrayBuffer);
    byteArray.forEach((element, index) => {
      // do something with each byte in the array
    });
  }
};

req.send(null);

ArrayBuffer介紹:
https://tr.javascript.info/arraybuffer-binary-arrays

fetch 用法:

A typical fetch request consists of two awaits:

let response = await fetch(url, options); // resolves with response headers
let result = await response.json(); // read body as json

Or, promise-style:

fetch(url, options)
  .then(response => response.json())
  .then(result => /* process result */)

Response properties:

  • response.status – HTTP code of the response,
  • response.ok – true is the status is 200-299.
  • response.headers – Map-like object with HTTP headers.

Methods to get response body:

  • response.json() – parse the response as JSON object,
  • response.text() – return the response as text,
  • response.formData() – return the response as FormData object (form/multipart encoding),
  • response.blob() – return the response as Blob (binary data with type),
  • response.arrayBuffer() – return the response as ArrayBuffer (pure binary data),

Fetch options so far:

  • method – HTTP-method,
  • headers – an object with request headers (not any header is allowed),
  • body – string/FormData/BufferSource/Blob/UrlSearchParams data to submit.

In the next chapters we’ll see more options and use cases.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *