Skip to main content

JavaScript
4 Things You Need to Know About Blobs



script.js

// AZUL CODING ---------------------------------------
// JavaScript - 4 Things You Need to Know About Blobs
// https://youtu.be/T0jmr8m-M9Y


// Part 1

let blob = new Blob(["Hello world!"], {
    type: "text/plain"
});

const downloadBtn = document.getElementById("download-btn");

downloadBtn.addEventListener("click", function() {
    let link = document.createElement("a");
    link.download = "hello.txt";
    link.href = URL.createObjectURL(blob);
    link.click();
});


// Part 2

let blobHTML = new Blob([document.documentElement.outerHTML], {
    type: "text/html"
});

downloadBtn.addEventListener("click", function() {
    let link = document.createElement("a");
    link.download = "index.html";
    link.href = URL.createObjectURL(blobHTML);
    link.click();
});


// Part 3

const fileInput = document.getElementById("file-input");
const container = document.getElementById("container");

fileInput.addEventListener("change", function() {
    let reader = new FileReader();
    reader.addEventListener("load", function() {
        container.innerHTML +=
            `<img src="${this.result}" width="180"/>`;
    });
    reader.readAsDataURL(this.files[0]);
});


// Part 4

let arr = new Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]);
let blobBin = new Blob([arr], {
    type: "application/octet-stream"
});

let reader = blobBin.stream().getReader();
reader.read().then(({value}) => {
    let text = new TextDecoder("utf-8").decode(value);
    console.log(text);
});

Enjoying this tutorial?


index.html

<!-- AZUL CODING --------------------------------------- -->
<!-- JavaScript - 4 Things You Need to Know About Blobs -->
<!-- https://youtu.be/T0jmr8m-M9Y -->


<!DOCTYPE html>
<html>
    <head>
        <title>Azul Coding</title>
        <style>
            body {
                margin: 30px;
                background-color: #03506E;
                color: white;
                font-size: 18px;
            }
            * {
                font-family: sans-serif;
            }
            #container {
                display: flex;
                flex-wrap: wrap;
                gap: 10px;
            }
            input[type=file] {
                display: block;
                margin-top: 10px;
                margin-bottom: 30px;
                border: 2px solid #49C8FC;
                padding: 5px;
            }
        </style>
        <script defer src="script.js"></script>
    </head>
    <body>
        <button id="download-btn">Download</button><hr><br>
        <label for="file-input">Select files:</label>
        <input id="file-input" type="file">
        <div id="container"></div>
    </body>
</html>