h5 blob的简单使用


blob 创建方式
  • 字符串
let myBlobParts = ['

Hello Leo

']; // 一个包含DOMString的数组 let myBlob = new Blob(myBlobParts, {type : 'text/html', endings: "transparent"}); // 得到 blob console.log(myBlob.size + " bytes size"); // Output: 31 bytes size console.log(myBlob.type + " is the type"); // Output: text/html is the type
  • 二进制数组
let hello = new Uint8Array([72, 101, 108, 108, 111]); // 二进制格式的 "hello" 
let blob = new Blob([hello, ' ', 'leo'], {type: 'text/plain'}); 
// Output: "Hello leo"
  • 分隔
let blob1 = new Blob(['

Hello Leo

'], {type : 'text/html', endings: "transparent"}); let blob2 = new Blob(['

Happy Boy!

'], {type : 'text/html', endings: "transparent"}); let slice1 = blob1.slice(16); let slice2 = blob2.slice(0, 16); await slice1.text(); // currtent slice1 value: "Leo" await slice2.text(); // currtent slice2 value: "

Happy " let newBlob = new Blob([slice2, slice1], {type : 'text/html', endings: "transparent"}); await newBlob.text(); // currtent newBlob value: "

Happy Leo

"

实际场景

  • 图片预览 data url / blob url /obj url


1.DataURL方式:

2.Blob方式:

图片预览 分片上传







图片预览 断点续传








js 下载数据







下载文件





图片压缩



生成pdf

客户端生成 PDF 示例

blob to arraybuffer
const buffer = new ArrayBuffer(16); 
const blob = new Blob([buffer]);

#### blob to arraybuffer

const blob = new Blob([1,2,3,4,5]);
const reader = new FileReader();
reader.onload = function() {
console.log(this.result);
}
reader.readAsArrayBuffer(blob);

#### ajax接受 blob arraybuffer

function GET(url, callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer'; // or xhr.responseType = "blob";
xhr.send();
xhr.onload = function(e) {
if (xhr.status != 200) {
alert("Unexpected status code " + xhr.status + " for " + url);
return false;
}
callback(new Uint8Array(xhr.response)); // or new Blob([xhr.response]); }; }