Response: bytes() 方法

基準線 2025
新推出

自 ⁨2025 年 1 月⁩ 起,此功能在最新的裝置和瀏覽器版本中均可正常工作。此功能可能無法在舊裝置或瀏覽器中工作。

注意:此功能在 Web Workers 中可用。

Response 介面的 bytes() 方法會讀取一個 Response 流直到完成。它返回一個解析為 Uint8Array 的 Promise。

語法

js
bytes()

引數

無。

返回值

解析為 Uint8Array 的 Promise。

異常

AbortError DOMException

請求已被 中止

TypeError

因以下原因之一而丟擲:

RangeError

建立關聯的 ArrayBuffer 時出現問題。例如,如果資料大小超過 Number.MAX_SAFE_INTEGER

示例

獲取和解碼檔案

以下程式碼展示瞭如何獲取一個文字檔案,將其正文作為 Uint8Array 返回,然後將其解碼為字串。

js
const response = await fetch("https://www.example.com/textfile.txt");
const textFile = await response.bytes();
const string = new TextDecoder().decode(textFile);
console.log(string);

獲取圖片檔案簽名

此示例演示瞭如何使用 bytes() 讀取多個圖片檔案的簽名位元組,並識別其型別。

HTML

首先,我們定義一個 <select> 元素用於選擇檔案型別,並附帶指示 WikiMedia commons 上特定檔案的相應值,以便獲取。

html
<label for="file-select">Choose a file:</label>

<select name="Files" id="file-select">
  <option value="">--Select an image type--</option>
  <option
    value="https://upload.wikimedia.org/wikipedia/commons/7/70/Example.png">
    PNG
  </option>
  <option
    value="https://upload.wikimedia.org/wikipedia/commons/a/a9/Example.jpg">
    JPG
  </option>
  <option
    value="https://upload.wikimedia.org/wikipedia/commons/8/8f/Example.gif">
    GIF89a
  </option>
</select>

JavaScript

程式碼首先檢查是否支援 bytes() 方法。如果支援該方法,則為 <select> 元素新增一個 change 事件 的事件處理程式。當值更改時,它會將所選內容的值(圖片檔案的 URL)傳遞給下面定義的 checkSignature() 方法。如果不支援該方法,則會記錄此資訊。

js
if ("bytes" in Response.prototype) {
  const selectFileElement = document.getElementById("file-select");
  selectFileElement.addEventListener("change", (event) => {
    try {
      checkSignature(event.target.value);
    } catch (e) {
      log(e);
    }
  });
} else {
  log("Response.bytes() not supported");
}

下面定義了 checkSignature() 方法。它會獲取給定 url 處的檔案的內容,並使用 response.bytes() 將其作為位元組陣列獲取。然後將初始位元組與常見檔案型別的初始簽名位元組進行比較。最後記錄檔名和檔案型別。

js
async function checkSignature(url) {
  if (url === "") return;
  log(`File: ${url}`);
  const response = await fetch(url);
  const image = await response.bytes();

  // File signatures from: https://en.wikipedia.org/wiki/List_of_file_signatures
  const jpgSignature = [0xff, 0xd8, 0xff, 0xe0];
  const pngSignature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
  const gif89aSignature = [0x47, 0x49, 0x46, 0x38, 0x39, 0x61];

  if (
    image
      .slice(0, jpgSignature.length)
      .every((byte, index) => byte === jpgSignature[index])
  ) {
    log(`JPG signature: FF D8 FF E0`);
  } else if (
    image
      .slice(0, pngSignature.length)
      .every((byte, index) => byte === pngSignature[index])
  ) {
    log(`PNG signature: 89 50 4E 47 0D 0A 1A 0A`);
  } else if (
    image
      .slice(0, gif89aSignature.length)
      .every((byte, index) => byte === gif89aSignature[index])
  ) {
    log(`GIF (GIF89a) signature: 47 49 46 38 39 61`);
  } else {
    log("Unknown format");
  }
}

結果

使用選擇列表選擇一個圖片型別。日誌隨後應顯示檔名以及根據檔案簽名確定的檔案型別。

規範

規範
Fetch
# dom-body-bytes

瀏覽器相容性

另見