Blob Data
Binary Data / Files: Blob Data
What is a Blob in JavaScript?
View Answer:
const blob = new Blob(data, {type: 'text/plain'});
How is a Blob object created?
View Answer:
const blob = new Blob(["This is a sample file content."], { type: "text/plain;charset=utf-8" });
Can you explain what a Blob constructor is in JavaScript?
View Answer:
var myBlobParts = ['<html><h2>This is heading</h2></html>'];
// an array consisting of a single DOMString
var myBlob = new Blob(myBlobParts, {
type: 'text/html',
endings: 'transparent',
}); // the blob
console.log(myBlob.size + ' bytes size');
// Output: 37 bytes size
console.log(myBlob.type + ' is the type');
// Output: text/html is the type
What are common uses for Blobs?
View Answer:
How do you read data from a Blob?
View Answer:
const blob = new Blob(["Hello, JavaScript!"], {type: "text/plain"});
const reader = new FileReader();
reader.readAsText(blob);
reader.onload = function() {
const text = reader.result;
console.log(text); // "Hello, JavaScript!"
};
Can Blob data be converted to a different format?
View Answer:
let blob = new Blob(["Hello World"], {type: "text/plain"});
let reader = new FileReader();
reader.onload = function() {
console.log(reader.result); // this will output the base64 string
}
reader.readAsDataURL(blob);
In this code, reader.result
will contain a base64 encoded data URL representing the text "Hello World".
Can Blob objects be sent to a server?
View Answer:
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width" />
<title>Fetch Request example</title>
</head>
<body>
<h1>Fetch Request example</h1>
<img src="" />
</body>
<script>
const myImage = document.querySelector("img");
const myRequest = new Request("flowers.jpg");
fetch(myRequest)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error, status = ${response.status}`);
}
return response.blob();
})
.then((myBlob) => {
const objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
})
.catch((error) => {
const p = document.createElement("p");
p.appendChild(document.createTextNode(`Error: ${error.message}`));
document.body.insertBefore(p, myImage);
});
</script>
</html>
How can you slice a part of a Blob?
View Answer:
// Assuming you have a Blob object named 'originalBlob'
// Define the start and end offsets for the slice
const startOffset = 10; // Starting offset in bytes
const endOffset = 50; // Ending offset in bytes (optional)
// Create a new Blob slice using the slice() method
const slicedBlob = originalBlob.slice(startOffset, endOffset);
// Use the slicedBlob as desired (e.g., upload or process it)
console.log('Sliced Blob:', slicedBlob);
How do you create a URL for a Blob?
View Answer:
// Assuming you have a Blob object named 'blobData'
// Create a URL for the Blob
const blobURL = URL.createObjectURL(blobData);
// Use the blobURL as desired (e.g., set it as the source of an image or a download link)
console.log('Blob URL:', blobURL);
What's the difference between Blob and ArrayBuffer?
View Answer:
Can Blobs be stored in IndexedDB?
View Answer:
// Open a database
var openDB = indexedDB.open('blobDB', 1);
openDB.onupgradeneeded = function() {
var db = openDB.result;
var store = db.createObjectStore('blobs', { autoIncrement: true });
};
openDB.onsuccess = function() {
var db = openDB.result;
var tx = db.transaction('blobs', 'readwrite');
var store = tx.objectStore('blobs');
// Create a new blob
var blob = new Blob(["Hello, world!"], {type: "text/plain"});
// Add the blob to IndexedDB
store.put(blob, 'hello.txt');
tx.oncomplete = function() {
db.close();
};
};
In this example, we're storing a simple text Blob in an IndexedDB store. The 'readwrite' parameter in db.transaction is used because we're writing data to the store. The blob is stored with the key 'hello.txt'.
What's the maximum size for a Blob?
View Answer:
What is a Blob URL?
View Answer:
// Create a Blob from a string
var blob = new Blob(["Hello, world!"], {type: "text/plain"});
// Create a Blob URL for the Blob
var blobURL = URL.createObjectURL(blob);
console.log(blobURL);
// This will log a Blob URL like: blob:http://your-site.com/12345678-1234-1234-1234567890ab
// Remember to revoke the Blob URL when you're done with it
URL.revokeObjectURL(blobURL);
In this example, blobURL
will be a Blob URL that you can use as a source in a <img>
, <audio>
, <video>
, <link>
, or <script>
tag, or you can open it in a new window or tab. It's important to revoke the Blob URL when you're done with it to free up memory.
What happens to Blob URLs when the page unloads?
View Answer:
// Create a Blob from a string
var blob = new Blob(["Hello, world!"], {type: "text/plain"});
// Create a Blob URL for the Blob
var blobURL = URL.createObjectURL(blob);
window.addEventListener('unload', function() {
// Revoke the Blob URL when the page unloads
URL.revokeObjectURL(blobURL);
});
In this example, the Blob URL blobURL
will be automatically revoked when the page unloads, freeing up memory. Note that Blob URLs should also be revoked as soon as they are no longer needed, even if the page is not unloading.
How can you manually release a Blob URL?
View Answer:
URL.revokeObjectURL(blobURL);
What's the use of the Blob's 'type' property?
View Answer:
// Create a Blob from a string with 'text/plain' MIME type
var textBlob = new Blob(["Hello, world!"], {type: "text/plain"});
console.log(textBlob.type); // Outputs: text/plain
// Create a Blob for a .png image with 'image/png' MIME type
var binaryData = []; // Add your binary image data here
var imageBlob = new Blob(binaryData, {type: "image/png"});
console.log(imageBlob.type); // Outputs: image/png
In this code, the 'type' property is used to define the content type of the data stored in the Blob object. This can be useful when serving the Blob data, as the receiving end can know how to handle the data based on its MIME type.
Is there a way to change data directly in a JavaScript Blob?
View Answer:
let blob = new Blob(['<html><h2>This is heading</h2></html>'], {
type: 'text/html',
endings: 'transparent',
});
let blobSlice = blob.slice(3, 25);
console.log(blobSlice.size); // returns 22
console.log(blob.type); // returns text/html
Can you name a use case for a JavaScript Blob?
View Answer:
<!-- download attribute forces the browser to download instead of navigating -->
<a download="hello.txt" href="#" id="link">Download</a>
<script>
let blob = new Blob(['Hello, world!'], { type: 'text/plain' });
link.href = URL.createObjectURL(blob);
</script>
What method is used to create an Object URL for a Blob?
View Answer:
const objectURL = URL.createObjectURL(object); // Can be file or Blob object
Is it possible to release an Object URL when it is no longer required?
View Answer:
let link = document.createElement('a');
link.download = 'hello.txt';
let blob = new Blob(['Hello, world!'], { type: 'text/plain' });
link.href = URL.createObjectURL(blob);
link.click();
URL.revokeObjectURL(link.href);
What is an alternative to URL.createObjectURL for creating an Object URL from a Blob, and what advantages does it offer?
View Answer:
let link = document.createElement('a');
link.download = 'hello.txt';
let blob = new Blob(['Hello, world!'], { type: 'text/plain' });
let reader = new FileReader();
reader.readAsDataURL(blob); // converts the blob to base64 and calls onload
reader.onload = function () {
link.href = reader.result; // data url
link.click();
};
What is the difference between creating an Object URL vs. converting a Blob into a base64-encoded string?
View Answer:
// Create a Blob
var blob = new Blob(["Hello, world!"], {type: "text/plain"});
// Convert Blob to base64
var reader = new FileReader();
reader.onloadend = function() {
var base64data = reader.result;
console.log(base64data); // "data:text/plain;base64,SGVsbG8sIHdvcmxkIQ=="
}
reader.readAsDataURL(blob);
// Create Blob URL
var blobURL = URL.createObjectURL(blob);
console.log(blobURL); // blob:http://your-site.com/12345678-1234-1234-1234567890ab
In this code, FileReader.readAsDataURL() is used to read the Blob as a base64-encoded string (data URL), while URL.createObjectURL() is used to create a Blob URL. These two methods can be used in different scenarios depending on the requirements of your application.
Creating a Blob URL is more memory-efficient and faster for large files. Converting to base64 increases size by about 33% but is necessary when data needs to be embedded or stored as text.
Does JavaScript provide a way to create a Blob of an image?
View Answer:
// take any image
let img = document.querySelector('img');
// make <canvas> of the same size
let canvas = document.createElement('canvas');
canvas.width = img.clientWidth;
canvas.height = img.clientHeight;
let context = canvas.getContext('2d');
// copy image to it (this method allows to cut image)
context.drawImage(img, 0, 0);
// we can context.rotate(), and do many other things on canvas
// toBlob is async opereation, callback is called when done
canvas.toBlob(function (blob) {
// blob ready, download it
let link = document.createElement('a');
link.download = 'example.png';
link.href = URL.createObjectURL(blob);
link.click();
// delete the internal blob reference, to let the browser clear memory from it
URL.revokeObjectURL(link.href);
}, 'image/png');