The responseType
property of the XMLHttpRequest object can be set to change the expected response type from the server. Possible values are the empty string (default), "arraybuffer"
, "blob"
, "document"
, "json"
, and "text"
. The response
property will contain the entity body according to responseType
, as an ArrayBuffer
, Blob
, Document
, JSON
, or string. This is null
if the request is not complete or was not successful.
This example reads an image as a binary file and creates an 8-bit unsigned integer array from the raw bytes. Note that this will not decode the image and read the pixels. You will need a png decoding library for that.
const req = new XMLHttpRequest();
req.open("GET", "/myfile.png", true);
req.responseType = "arraybuffer";
req.onload = (event) => {
const arrayBuffer = req.response;
if (arrayBuffer) {
const byteArray = new Uint8Array(arrayBuffer);
byteArray.forEach((element, index) => {
});
}
};
req.send(null);
You can also read a binary file as a Blob
by setting the string "blob"
to the responseType
property.
const req = new XMLHttpRequest();
req.open("GET", "/myfile.png", true);
req.responseType = "blob";
req.onload = (event) => {
const blob = req.response;
};
req.send();
The loadBinaryResource()
function shown below loads binary data from the specified URL, returning it to the caller.
function loadBinaryResource(url) {
const req = new XMLHttpRequest();
req.open("GET", url, false);
req.overrideMimeType("text/plain; charset=x-user-defined");
req.send(null);
return req.status === 200 ? req.responseText : "";
}
The magic happens in line 5, which overrides the MIME type, forcing the browser to treat it as plain text, using a user-defined character set. This tells the browser not to parse it, and to let the bytes pass through unprocessed.
const filestream = loadBinaryResource(url);
const abyte = filestream.charCodeAt(x) & 0xff;
The example above fetches the byte at offset x
within the loaded binary data. The valid range for x
is from 0 to filestream.length-1
.
See downloading binary streams with XMLHttpRequest for a detailed explanation.
The send
method of the XMLHttpRequest has been extended to enable easy transmission of binary data by accepting an ArrayBuffer
, Blob
, or File
object.
The following example creates a text file on-the-fly and uses the POST
method to send the "file" to the server. This example uses plain text, but you can imagine the data being a binary file instead.
const req = new XMLHttpRequest();
req.open("POST", url, true);
req.onload = (event) => {
};
const blob = new Blob(["abc123"], { type: "text/plain" });
req.send(blob);
You can send JavaScript typed arrays as binary data as well.
const array = new Uint8Array(512).map((v, i) => i);
const xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.send(array);
This is building a 512-byte array of 8-bit integers and sending it; you can use any binary data you'd like, of course.