Home  >  Article  >  Web Front-end  >  How to upload blob using JavaScript?

How to upload blob using JavaScript?

王林
王林forward
2023-09-07 09:41:021750browse

JavaScript 如何上传 blob?

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

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

JavaScript can use XMLHttpRequest or fetch API to upload blobs.

1. Using XMLHTTPRequest

XMLHttpRequest (XHR) is an object-like API whose methods transfer data between a web browser and a web server. The browser's JavaScript environment provides this object. Usually used to send and receive data asynchronously without restarting the website. This makes it possible to enjoy dynamic, user-friendly and fast web pages.

Example

This is an example of using XMLHttpRequest to upload a Blob -

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 use some blob data to make a POST request to the /upload endpoint of the backend API. After the server responds successfully, we log out the response.

2. Use GetAPI

The Fetch API allows you to make requests to a server and retrieve data from it. It is built into modern web browsers and can be used to make GET and POST requests. The Fetch API uses the fetch() method, which returns a Promise that resolves to a Response object. The Response object can then be used to access the data returned by the server. The Fetch API is often used as a replacement for 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 web page hosting server.

This is an example of using fetch to upload a Blob -

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);
});

So this way you can upload blob data from frontend vanilla JavaScript to server using XMLHTTPRequest or fetch API without using any third party library.

The above is the detailed content of How to upload blob using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete