傳送和接收二進位制資料
接收二進位制資料
XMLHttpRequest 物件的 responseType 屬性可以設定,以更改來自伺服器的預期響應型別。可能的值為空字串(預設值)、"arraybuffer"、"blob"、"document"、"json" 和 "text"。response 屬性將根據 responseType 包含實體主體,作為 ArrayBuffer、Blob、Document、JSON 或字串。如果請求未完成或未成功,則此值為 null。
此示例將影像作為二進位制檔案讀取,並從原始位元組建立 8 位無符號整數陣列。請注意,這不會解碼影像並讀取畫素。這可以透過 ImageDecoder 介面完成。
js
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);
您還可以透過將字串 "blob" 設定為 responseType 屬性,將二進位制檔案讀取為 Blob。
js
const req = new XMLHttpRequest();
req.open("GET", "/myfile.png", true);
req.responseType = "blob";
req.onload = (event) => {
const blob = req.response;
// …
};
req.send();
傳送二進位制資料
XMLHttpRequest 的 send 方法已擴充套件,允許透過接受 ArrayBuffer、Blob 或 File 物件輕鬆傳輸二進位制資料。
以下示例即時建立了一個文字檔案,並使用 POST 方法將此“檔案”傳送到伺服器。此示例使用純文字,但您可以想象資料是二進位制檔案。
js
const req = new XMLHttpRequest();
req.open("POST", url, true);
req.onload = (event) => {
// Uploaded
};
const blob = new Blob(["abc123"], { type: "text/plain" });
req.send(blob);
以二進位制資料形式傳送型別化陣列
您也可以以二進位制資料形式傳送 JavaScript 型別化陣列。
js
// Create a new array with fake data (Consecutive numbers (0 - 255), looping back to 0)
const array = new Uint8Array(512).map((v, i) => i);
const xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.send(array);
這是在構建一個 512 位元組的 8 位整數陣列併發送它;當然,您可以使用任何您想要的二進位制資料。
提交表單和上傳檔案
請參閱 FormData。