πŸ” AJAX Request & Response Lifecycle
Estimated reading: 5 minutes 304 views

AJAX – Handling Binary Data: Complete Guide with Practical Examples


Introduction – Why Handle Binary Data with AJAX?

While AJAX is often used for sending and receiving text or JSON, many modern web applications also require transferring binary dataβ€”like images, PDFs, audio files, and raw byte streams. Whether you’re fetching a downloadable PDF, streaming video, or uploading files, mastering binary data handling with AJAX is essential.

Binary handling becomes particularly important in use cases like:

  • File previews before upload
  • Receiving blobs (images, PDFs) from servers
  • Sending binary data for APIs or cloud storage

In this guide, you’ll learn:

  • What binary data is in the context of AJAX
  • How to handle binary responses using XMLHttpRequest and fetch()
  • How to send and receive blobs and ArrayBuffers
  • Real-world examples and best practices

What Is Binary Data in AJAX?

Binary data refers to non-textual, raw byte data, such as:

  • Images (.jpg, .png)
  • PDF files
  • Audio (.mp3, .wav)
  • Videos (.mp4)
  • Documents and custom binary protocols

In JavaScript, this is handled using types like:

  • Blob
  • ArrayBuffer
  • TypedArray (e.g., Uint8Array, Float32Array)

XMLHttpRequest with responseType = "blob" or "arraybuffer"

Example – Download Image as Blob

var xhr = new XMLHttpRequest();
xhr.open("GET", "photo.jpg", true);
xhr.responseType = "blob";

xhr.onload = function () {
  if (xhr.status === 200) {
    var imgURL = URL.createObjectURL(xhr.response);
    document.getElementById("preview").src = imgURL;
  }
};

xhr.send();

Explanation:

  • responseType = "blob" tells the browser to expect binary data.
  • URL.createObjectURL() converts the blob into a usable object URL for previews.

Example – Receiving Binary Data as ArrayBuffer

var xhr = new XMLHttpRequest();
xhr.open("GET", "sound.wav", true);
xhr.responseType = "arraybuffer";

xhr.onload = function () {
  if (xhr.status === 200) {
    console.log("Received byte length:", xhr.response.byteLength);
    // Further processing: e.g., decodeAudioData()
  }
};

xhr.send();

This is useful when you need to manually manipulate the byte stream (e.g., audio decoding, file parsing).


Handling Binary Data with Fetch API

Example – Fetch PDF File as Blob

fetch("file.pdf")
  .then(response => response.blob())
  .then(blob => {
    const url = URL.createObjectURL(blob);
    window.open(url, "_blank");
  })
  .catch(error => console.error("Error:", error));

With fetch(), you can use .blob() or .arrayBuffer() to read binary responses easily.


Sending Binary Data Using AJAX

Upload File Using FormData (Recommended)

<input type="file" id="fileInput" />
<button onclick="uploadFile()">Upload</button>
function uploadFile() {
  const file = document.getElementById("fileInput").files[0];
  const formData = new FormData();
  formData.append("upload", file);

  fetch("upload.php", {
    method: "POST",
    body: formData
  })
    .then(res => res.text())
    .then(msg => alert(msg));
}

FormData is ideal for uploading binary files. It handles headers and encoding automatically.


Sending Raw Binary via XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open("POST", "upload.php", true);
xhr.setRequestHeader("Content-Type", "application/octet-stream");

xhr.onload = function () {
  console.log(xhr.responseText);
};

xhr.send(binaryData); // Could be an ArrayBuffer or Blob

Use this approach for APIs that expect binary payloads directly, not wrapped in multipart/form-data.


PHP Backend for Binary File Upload

<?php
if ($_FILES['upload']) {
  move_uploaded_file($_FILES['upload']['tmp_name'], 'uploads/' . $_FILES['upload']['name']);
  echo "File uploaded!";
} else {
  echo "No file received.";
}
?>

This script supports uploads from AJAX + FormData combination.


Blob vs ArrayBuffer – What’s the Difference?

FeatureBlobArrayBuffer
StructureImmutable raw dataFixed-length binary buffer
Use CasePreviews, downloads, uploadsByte-level operations
ConversionURL.createObjectURL(), FileReaderDataView, TypedArray
Better forImages, PDFs, mediaCustom binary formats

Common Mistakes to Avoid

Mistake Fix
Using .text() for binary responseUse .blob() or .arrayBuffer()
Forgetting responseType in XHRSet it to "blob" or "arraybuffer"
Manually setting content-type for FormDataLet browser handle it
Opening large files directly in DOMUse object URLs (URL.createObjectURL(blob))

Summary – Recap & Takeaways

Handling binary data with AJAX is essential for modern applications that deal with media, documents, and raw data. With XMLHttpRequest and fetch(), developers can seamlessly send and receive binary content, show previews, and integrate with file upload systems.

Key Takeaways:

  • Use responseType = "blob" or .blob() to receive binary files
  • Use FormData for easy file uploads
  • Use URL.createObjectURL() to show image/video previews
  • Prefer fetch() for cleaner syntax and Promise support

Next Steps:

  • Try loading an image gallery using blob URLs
  • Create a file uploader that handles multiple file types
  • Decode audio streams using ArrayBuffer and Web Audio API

FAQs – Handling Binary Data in AJAX


How do I show a binary image response on the page?
Convert the blob into an object URL and assign it to an <img> tag:

img.src = URL.createObjectURL(blob);

Can I download a file using AJAX and trigger a save prompt?
Yes! Create a download link programmatically:

const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "file.pdf";
link.click();

What is the best way to upload binary files with AJAX?
Use FormData. It simplifies file uploads and works across all browsers.


Should I use Blob or ArrayBuffer?
Use Blob for general file handling (images, documents) and ArrayBuffer when you need to manipulate raw byte-level data.


How do I read binary files on the client side before uploading?
Use the FileReader API:

const reader = new FileReader();
reader.onload = function () {
  const arrayBuffer = reader.result;
};
reader.readAsArrayBuffer(file);

Share Now :
Share

AJAX – Handling Binary Data

Or Copy Link

CONTENTS
Scroll to Top