Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Blob的了解 #83

Open
gdutwyg opened this issue Oct 23, 2019 · 0 comments
Open

Blob的了解 #83

gdutwyg opened this issue Oct 23, 2019 · 0 comments
Labels

Comments

@gdutwyg
Copy link
Owner

gdutwyg commented Oct 23, 2019

Blob是当前Web前端很常用的数据格式,是Binary Large Object(大型二进制对象)的缩写。代表原始的二进制数据。和ArrayBuffer类似,都是二进制数据的容器。

在HTML5新的标准中File对象的内部就使用了Blob,从标签中获取的File对象即是一个Blob实例。

this.files[0] instanceof Blob  // true

语法

var blob = new Blob(data[, options]))

data是一组数据,所以必须是数组,即使只有一个字符串也必须用数组装起来.
参数options是对这一Blob对象的配置属性,目前只有一个type,也就是相关的MIME。
type的值:

  • ‘text/csv,charset=UTF-8’ 设置为csv格式,并设置编码为UTF-8,
  • ’text/html’ 设置成html格式。
  • 等等...
var blob = new Blob(['hello world'],{type: 'text/html'})

属性:

blob.size   //Blob大小(以字节为单位)
blob.type   //Blob的MIME类型,如果是未知,则是“ ”(空字符串)

方法:

Blob.slice([start[, end[, contentType]]])

slice()返回一个新的Blob对象,包含了源Blob对象中指定范围内的数据。
start 开始索引 默认是0
end 结束索引 可以为负数,语法类似于数组的slice方法.默认值为最后一个索引
contentType 可选,字符串,新的Blob对象的MIME类型,这个值将会成为新的Blob对象的type属性的值,不传则默认为一个空字符串

Blob.text()
将Blob解析为文本流,它返回一个promise

Blob.arrayBuffer()
将Blob解析为二进制数据ArrayBuffer,返回一个promise

var blob = new Blob(['hello world'],{type: 'text/html'})
var newBlob = blob.slice(0,1,'text/html')
newBlob.text().then((resolve) => {
  console.log(resolve) // h
})

Blob的使用

  • 创建一个URL来指向Blob
<a download="data.txt" id="getData">下载</a>   

var data= 'Hello world!';  
var blob = new Blob([data], {   
  type: 'text/html,charset=UTF-8'   
});
window.URL = window.URL || window.webkitURL; 
document.querySelector("#getData").href = URL.createObjectURL(blob); // 生成一个临时链接,在内存
  • 大文件分割上传
// 上传函数
function upload () {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/server', true);
  xhr.onload = function(e) { ... };
  xhr.send(blobOrFile);
}
document.querySelector('input[type="file"]').addEventListener('change', function(e) {
  var blob = this.files[0]; // file对象 也是一个blob对象
   // 以1M的大小上传切割
  const BYTES_PER_CHUNK = 1024 * 1024; // 1MB chunk sizes.
  const SIZE = blob.size;

  var start = 0;
  var end = BYTES_PER_CHUNK;

  while(start < SIZE) {
    upload(blob.slice(start, end));

    start = end;
    end = start + BYTES_PER_CHUNK;
  }
}, false);
  • 隐藏视频源路径
var video = document.getElementById('video');
var obj_url = window.URL.createObjectURL(blob);
video.src = obj_url;
video.play()
window.URL.revokeObjectURL(obj_url);

参考

Blob对象

@gdutwyg gdutwyg changed the title blob的了解 Blob的了解 Oct 24, 2019
@gdutwyg gdutwyg added the js label Oct 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant