How can JavaScript upload a blob?


Blob stands for Binary Large Object and they are used to store binary data like images, audio or other multimedia objects, and sometimes binary executable code is also stored as a blob.

We can use JavaScript to upload blob like any other data file.

JavaScript can upload a Blob using the XMLHttpRequest or fetch API.

1. Using XMLHTTPRequest

XMLHttpRequest (XHR) is an API in the form of an object whose methods transfer data between a web browser and a web server. The JavaScript environment of the browser provides the object. It is usually used to send and receive data asynchronously without restarting the website. This makes it possible to enjoy a dynamic, user-friendly, and speedy web page.

Example

Here is an example of uploading a Blob using XMLHttpRequest −

var blob = new Blob(["Some conventional data"], { type: "text/plain" }); var xhr = new XMLHttpRequest(); xhr.open("POST", "/upload", true); xhr.onload = function (e) { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send(blob);

Here we are making a POST request to the /upload endpoint of our backend API with some blob data. And on the successful response of the server, we are logging out the response.

2. Using Fetch API

The Fetch API allows you to make requests to servers and retrieve data from them. It is built into modern web browsers and can be used to make both GET and POST requests. The Fetch API uses the fetch() method, which returns a promise that resolves to a Response object. This Response object can then be used to access the data returned by the server. The Fetch API is often used as an alternative to the older XMLHttpRequest API and is more modern and user-friendly. It is also more versatile, as it can be used to make requests to servers other than the one the webpage is hosted on.

Here is an example of uploading a Blob using fetch −

var blob = new Blob(["Some conventional data"], { type: "text/plain" }); var formData = new FormData(); formData.append("file", blob); fetch("/upload", { method: "POST", body: formData, }) .then((response) => response.text()) .then((responseText) => { console.log(responseText); });

Therefore, in this way, you can either use the XMLHTTPRequest or fetch API to upload blob data to the server from the frontend vanilla JavaScript without using any third party library.

Updated on: 06-Feb-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements