(async() => {
const c = document.body;
imageBlob = () => {
const svg = `<svg viewBox="0 0 200 200" width="80" height="80" xmlns="http://www.w3.org/2000/svg"><path fill="#FF0066" d="M31.5,-16.8C35.9,3.2,31,19.6,16.3,32.8C1.5,46,-23.2,55.9,-36.6,46.9C-50.1,38,-52.3,10.1,-44.3,-14.8C-36.4,-39.8,-18.2,-61.9,-2.3,-61.2C13.6,-60.4,27.2,-36.8,31.5,-16.8Z" transform="translate(100 100)" /></svg>`;
return new Blob(
[svg], {
type: 'image/svg+xml'
}
);
}
htmlBlob = () => {
return new Blob(
['<span>HTML <b style="color: red">blob</b></span>'], {
type: 'text/html'
}
);
}
jsonBlob = type => {
const json = {
a: 1,
b: {
c: 'val'
}
}
const jsonStr = JSON.stringify(json);
return new Blob([jsonStr], {
type
});
}
// Blob instances you might get from: await response.blob()
// blob.type is set from 'Content-Type' header of its response
const blobs = [
imageBlob(), // 1
htmlBlob(), // 2
jsonBlob('application/json'), // 3
jsonBlob('application/octet-stream'), // 4
jsonBlob('???/???') // 5
]
for (const [i, b] of Object.entries(blobs)) {
c.append(Object.assign(document.createElement('h3'), {
textContent: `${1+parseInt(i)}. ${b.type}:`
})) // b.type === 'Content-Type'━━┛
if (b.type.startsWith('text/html')) { // 1
const text = await b.text();
c.append(Object.assign(document.createElement('div'), {
innerHTML: text
}));
} else if (b.type.startsWith('image/')) { // 2
c.append(Object.assign(document.createElement('img'), {
src: URL.createObjectURL(b)
}));
} else if (b.type.startsWith('application/json')) { // 3
c.append(Object.assign(document.createElement('pre'), {
textContent: JSON.stringify(JSON.parse(await b.text()), null, ' ')
}));
} else if (b.type.startsWith('application/octet-stream')) { // 4
c.append(Object.assign(document.createElement('a'), {
textContent: 'download json',
href: URL.createObjectURL(b),
download: 'data.json'
}));
} else { // 5
// .... create a clone Response from blob
// -> response2 = new Response(await response1.blob())
const response2 = new Response(b);
const b2 = await response2.blob(); // .json() .text(),...
const text2 = await b2.text();
console.log('blob2', text2, b2.type);
// Blogs are b === b2
const text = await b.text();
console.log('blob1', text, b.type);
console.log('blob2 === blob1', text === text2); // true
}
}
c.append(Object.assign(document.createElement('h3'), {
innerHTML: ` <br> `
}))
})()