Blob and File Web API Example
by Peng Jie
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>`Blob` and `File` Web API Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet">
<link rel="stylesheet" href="//cdn.rawgit.com/necolas/normalize.css/master/normalize.css">
<link rel="stylesheet" href="//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">
</head>
<body>
<div id="app">
<div class="container">
<h3>Blob and File Web API Example</h3>
<hr>
<div class="row">
<div class="column">
<label for="upload" class="button file-label">Select Image</label>
<input
id="upload"
class="hidden"
type="file"
accept="image/*"
/>
</div>
</div>
<div class="row">
<div class="column">
<img id="upload-image" />
</div>
</div>
</div>
</div>
</body>
</html>
CSS
boy {
font-family: 'Source Code Pro';
}
#app {
margin-top: 25px;
}
.file-label {
width: 15rem;
}
input[type=file].hidden {
visibility: hidden;
width: 15rem;
margin-left: -15rem;
}
JavaScript
const uploadButton = document.getElementById('upload');
const imgDOM = document.getElementById('upload-image');
function createImageFromFile(img, file) {
return new Promise((resolve, rejfect) => {
img.src = URL.createObjectURL(file);
img.onload = () => {
URL.revokeObjectURL(img.src);
resolve(img);
};
img.onerror = () => reject('Failure to load image.');
});
}
function getFileBase64Encode(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
function handleFiles() {
const fileList = this.files;
const [file] = fileList;
const p1 = createImageFromFile(imgDOM, file);
const p2 = getFileBase64Encode(file);
Promise.all([p1, p2])
.then(result => {
const [img, b64] = result;
// fixed image width, height
img.width = 150;
img.height = 150;
console.log(b64);
});
}
uploadButton.addEventListener('change', handleFiles, false);