Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow can JavaScript upload a blob ?

How can JavaScript upload a blob ?

There are many ways to upload a blob (a group of bytes that holds the data stored in a file) in JavaScript, using XMLHttpRequest, Fetch API, jQuery. In this tutorial, we will discuss the two most common ways that are supported by a majority of the browsers.

Note: To test our HTTP request, you can use minimal express server. You can also use any online testing tool like webhook.site.

Fetch API: The Fetch API allows web browsers to send and receive data from the servers through HTTP requests. It is an easy-to-use version of XMLHttpRequest. The fetch() method returns a Promise which then can be chained with then() and catch() for better error handling. It is supported by all the modern browsers except IE.

Syntax:

fetch( url,  // API endpoint
{
    method:"",  // HTTP Method (GET, POST, PUT, DELETE)
    body: {},   // Data to be sent
}).then(response => {

    // handle the response
})
.catch(e => {

    // handle the error
});

Example:

JavaScript




<script>
    function uploadBlob() {
        const blob =
            new Blob(
                ["This is some important text"],
                { type: "text/plain" }
            );
  
        // Creating a new blob  
        // Hostname and port of the local server
        fetch('http://localhost:3000', {
  
            // HTTP request type
            method: "POST",
  
            // Sending our blob with our request
            body: blob
        })
        .then(response => alert('Blob Uploaded'))
        .catch(err => alert(err));
    }
  
    document.addEventListener('load', uploadBlob())
</script>


Output:

AJAX: It is a set of web applications that can send and retrieve data from a server asynchronously without reloading the current page. Please import or load jQuery before calling the ajax function.

Syntax:

$.ajax({
    url: "",       // API Endpoint
    type: "",      // HTTP Method (GET, POST, PUT, DELETE)
    data: {},      // Data to be sent
    
    // Specifies how the form-data should be encoded
    enctype: 'multipart/form-data',
    success: function(data) {
    
    // Handle the response
}, error: function(e) {

    // Handle the error
}
});

Example:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <script src=
    </script>
</head>
  
<body>
    <script>
        function uploadBlob() {
            const blob = new Blob(
                ["This is some important text"],
                { type: "text/plain" }
            );
  
            // Creating a new blob  
            $.ajax({
  
                // Hostname and port of the local server
                url: "http://localhost:3000/",
  
                // HTTP request type
                type: "POST",
  
                // Sending blob with our request
                data: blob,
                processData: false,
                contentType: false,
                success: function (data) {
                    alert('Blob Uploaded')
                },
                error: function (e) {
                    alert(e);
                }
            });
  
        }
        $(document).on('load', uploadBlob());
    </script>
</body>
  
</html>


Output:

RELATED ARTICLES

Most Popular

Recent Comments