What is a Blob?

A blob object represents a chuck of bytes that holds data of a file.

But a blob is not a reference to a actual file, it may seem like it is.

A blob has its size and MIME type just like a file has.

Blob data is stored in the memory or filesystem depending on the browser and blob size. A blob can be used like a file wherever we use files.

Most APIs for working with blobs are asynchronous. But synchronous versions of APIs are also available so that they can be used in Web Workers.

Content of a blob can be read as ArrayBuffer and therefore it makes blobs very handy to store binary data.

Creating a Blob

A blob can be created using Blob class.

//first arguement must be an regular array. The array can be of any javascript objects. Array can contain array to make it multi dimensional
//second parameter must be a BlogPropertyBag object containing MIME property
var myBlob = new Blob(["This is my blob content"], {type : "text/plain"});

In the above code we saw how we can insert data to a blob. We can read data from a blob using FileReader Class.

Example:

JS code:

//first arguement must be an regular array. The array can be of any javascript objects. Array can contain array to make it multi dimensional
//second parameter must be a BlogPropertyBag object containing MIME property
var myBlob = new Blob(["This is my blob content"], {type : "text/plain"});
var myReader = new FileReader();
//handler executed once reading(blob content referenced to a variable) from blob is finished.
myReader.addEventListener("loadend", function(e){
document.getElementById("paragraph").innerHTML = e.srcElement.result;//prints a string
});
//start the reading process.
myReader.readAsText(myBlob);

HTML code:

<p id="paragraph"></p>

result :This is my blob content

Blob URLs

As we have file:// URLs, referencing to a real file in local filesystem.

Similarly we have blob:// URLs referencing to an blob. blob:// URLs can be used almost wherever we use regular URLs.

A blob:// URL to a blob can be obtained using the createObjectURL object.

example:

JS code:

//cross browser
window.URL = window.URL || window.webkitURL; var blob = new Blob(['body { background-color: yellow; }'], {type: 'text/css'}); var link = document.createElement('link');
link.rel = 'stylesheet';
//createObjectURL returns a blob URL as a string.
link.href = window.URL.createObjectURL(blob);
document.body.appendChild(link);

the result is the document color is yellow.

revokeObjectURL(url : String) : return undefined

function is to frees the resources associated with the url created by createObjectURL().

Remote data as Blobs

We can retrieve remote files using AJAX and and store the file data inside a blob.

AJAX API provides us a method to download and store remote files in form of blobs.

example:

JS code:

var xhr = new XMLHttpRequest();
xhr.open("GET", "/favicon.png");
xhr.responseType = "blob";//force the HTTP response, response-type header to be blob
xhr.onload = function()
{
document.getElementsByTagName("body")[0].innerHTML = xhr.response;//xhr.response is now a blob object
}
xhr.send();

Result:[object Blob]

We can get the blob content in an ArrayBuffer and then analyze the ArrayBuffer as binary data. This can be done using FileReader.readAsArrayBuffer() method.

example:

JS code:

var xhr = new XMLHttpRequest();
xhr.open("GET", "/favicon.png");
//although we can get the remote data directly into an arraybuffer using the string "arraybuffer" assigned to responseType property.
//For the sake of example we are putting it into a blob and then copying the blob data into an arraybuffer.
xhr.responseType = "blob"; function analyze_data(blob)
{
var myReader = new FileReader();
myReader.readAsArrayBuffer(blob) myReader.addEventListener("loadend", function(e)
{
var buffer = e.srcElement.result;//arraybuffer object
});
} xhr.onload = function()
{
analyze_data(xhr.response);
}
xhr.send();

Conclusion

Blobs are very useful while working with binary remote files. A blob can be very large i.e., can contain audio and video data too. They can be created dynamically and using blob URLs they can be used as files. You can use them in many different ways to make them more useful. Thanks for reading.

Intro of BLOB

Blobs are immutable objects that represent raw data.

File is a derivation of Blob that represents data from the file system.

UseFileReader to read data from a Blob or File.

Blobs allow you to construct file like objects on the client that you can pass to apis that expect urls instead of requiring the server provides the file. For example, you can construct a blob containing the data for an image, use URL.createObjectURL() to generate a url, and pass that url to HTMLImageElement.src to display the image you created without talking to a server.

Constructors

new Blob(blobParts : Array, [blobPropertyBag : Object]) : Blob

blobPropertyBag : {
type String A valid mime type such as 'text/plain'
endings String Must be either 'transparent' or 'native'
}

Creates a new Blob. The elements of blobParts must be of the types ArrayBufferArrayBufferViewBlob, or String. If ending is set to'native', the line endings in the blob will be converted to the system line endings, such as '\r\n' for Windows or '\n' for Mac.

var blob = new Blob(['foo', 'bar']);

console.log('size=' + blob.size); // result is size=6
console.log('type=' + blob.type);//result is type= var testEndings = function(string, endings) {
var blob = new Blob([string], { type: 'plain/text',
endings: endings });
var reader = new FileReader();
reader.onload = function(event){
console.log(endings + ' of ' + JSON.stringify(string) +
' => ' + JSON.stringify(reader.result));
};
reader.readAsText(blob);
}; testEndings('foo\nbar', 'native');//result is native of "foo\nbar" => "foo\r\nbar"
testEndings('foo\r\nbar', 'native');//result is native of "foo\r\nbar" => "foo\r\nbar"
testEndings('foo\nbar', 'transparent');//result is transparent of "foo\nbar" => "foo\nbar"
testEndings('foo\r\nbar', 'transparent');//result is transparent of "foo\r\nbar" => "foo\r\nbar"

Instance Properties

 

size : Number  readonly

The size of the blob in bytes.

type : String  readonly

The type of the blob.

Instance Methods

 
 
slice([start = 0 : Number, [end : Number, [contentType = '' : String]]]) : Blob

Returns a new blob that contains the bytes start to end - 1 from this. If start or end is negative, the value is added to this.sizebefore performing the slice. If end is not specified, this.size is used. The returned blob's type will be contentType if specified, otherwise it will be ''.

var blob = new Blob(['foo', 'bar'], { type: 'plain/text',
endings: 'native' });
console.log('blob size:', blob.size); //result is blob size: 6
console.log('blob type:', blob.type);//result is blob type: plain/text var copy = blob.slice()
console.log('copy size:', copy.size);//result is copy size: 6
console.log('copy type:', copy.type);//result is copy type: var slice = blob.slice(1, 4, 'foo-type')
console.log('slice size:', slice.size);//resut is slice size: 3
console.log('slice type:', slice.type);//result is slice type: foo-type
 

最新文章

  1. mysql 连接池超时
  2. bzoj 3196: Tyvj 1730 二逼平衡树
  3. 家里蹲大学数学杂志 Charleton University Mathematics Journal 官方目录[共七卷493期,6055页]
  4. ubuntu 下安装redis 以及php扩展
  5. Express中使用mongodb存储session
  6. shell date
  7. MAC 下安装PIL
  8. HTML5 ArrayBuffer:类型化数组 (二)
  9. Openjudge-计算概论(A)-骑车与走路
  10. SpringMVC:学习笔记(2)——RequestMapping及请求映射
  11. 一小时学会ECMAScript6新特性
  12. DotNetty 实现 Modbus TCP 系列 (二) ModbusFunction 类图及继承举例
  13. python正则提取关键字
  14. 2017-12-15python全栈9期第二天第七节之布尔值转数字
  15. 《前端福音,vue.js 之豆瓣电影组件大揭秘-video》
  16. BZOJ-7-2655: calc-DP-拉格朗日插值
  17. music cube
  18. 【Java集合源码剖析】Hashtable源码剖析
  19. java8 新特性 Stream
  20. python学习笔记(日志系统实现)

热门文章

  1. [Guava源代码阅读笔记]-Basic Utilities篇-1
  2. Android二维码工具zxing使用
  3. class文件结构浅析(2)
  4. C++11 并发指南五(std::condition_variable 详解)(转)
  5. 【Access2007】Access2007的打开方式
  6. JrtpLib vs2012环境下编译及使用 GotoFirstSourceWithData 方法 进不去
  7. hdu 1081 &amp;amp; poj 1050 To The Max(最大和的子矩阵)
  8. uboot下载地址
  9. kubernetes集群管理命令(二)
  10. pygame 安装教程