JavaScript - Blob & File API
Overview
Estimated time: 10–15 minutes
The Blob and File APIs allow you to work with binary data and files in the browser.
Learning Objectives
- Create and manipulate Blob objects.
- Read files from user input using the File API.
Prerequisites
Blob Example
const blob = new Blob(['Hello, world!'], { type: 'text/plain' });
File API Example
const input = document.querySelector('input[type=file]');
input.addEventListener('change', function() {
const file = input.files[0];
const reader = new FileReader();
reader.onload = function(e) {
console.log(e.target.result);
};
reader.readAsText(file);
});
Common Pitfalls
- File operations are asynchronous and may require user permission.
Summary
The Blob and File APIs are essential for handling files and binary data in web apps.