blob javascript code example
Example 1: url to blob js
fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
.then(res => res.blob())
.then(blob => {
let objectURL = URL.createObjectURL(blob);
let myImage = new Image();
myImage.src = objectURL;
document.getElementById('myImg').appendChild(myImage)
});
Example 2: javascript create blob or data/image from image url
function convertImgToBase64URL(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'), dataURL;
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
convertImgToBase64URL('http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png', function(base64Img){
alert('it works');
$('.output').find('img').attr('src', base64Img);
});
Example 3: blob to text javascript
<RESPONSE PROMISE>
.then(r=>r.blob())
.then(r=>{
console.log(r.type)
return new Response(r)
})
.then(r=>
r.text()
)
.then(console.log)
Example 4: upload bloob javascript
var fd = new FormData();
fd.append('fname', 'test.wav');
fd.append('data', soundBlob);
$.ajax({
type: 'POST',
url: '/upload.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});