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.

  1. //first arguement must be an regular array. The array can be of any javascript objects. Array can contain array to make it multi dimensional
  2. //second parameter must be a BlogPropertyBag object containing MIME property
  3. 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:

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

HTML code:

  1. <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:

  1. //cross browser
  2. window.URL = window.URL || window.webkitURL;
  3.  
  4. var blob = new Blob(['body { background-color: yellow; }'], {type: 'text/css'});
  5.  
  6. var link = document.createElement('link');
  7. link.rel = 'stylesheet';
  8. //createObjectURL returns a blob URL as a string.
  9. link.href = window.URL.createObjectURL(blob);
  10. 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:

  1. var xhr = new XMLHttpRequest();
  2. xhr.open("GET", "/favicon.png");
  3. xhr.responseType = "blob";//force the HTTP response, response-type header to be blob
  4. xhr.onload = function()
  5. {
  6. document.getElementsByTagName("body")[0].innerHTML = xhr.response;//xhr.response is now a blob object
  7. }
  8. 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:

  1. var xhr = new XMLHttpRequest();
  2. xhr.open("GET", "/favicon.png");
  3. //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.
  4. xhr.responseType = "blob";
  5.  
  6. function analyze_data(blob)
  7. {
  8. var myReader = new FileReader();
  9. myReader.readAsArrayBuffer(blob)
  10.  
  11. myReader.addEventListener("loadend", function(e)
  12. {
  13. var buffer = e.srcElement.result;//arraybuffer object
  14. });
  15. }
  16.  
  17. xhr.onload = function()
  18. {
  19. analyze_data(xhr.response);
  20. }
  21. 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.

  1. var blob = new Blob(['foo', 'bar']);
  2.  
  3. console.log('size=' + blob.size); // result is size=6
  4. console.log('type=' + blob.type);//result is type=
  5.  
  6. var testEndings = function(string, endings) {
  7. var blob = new Blob([string], { type: 'plain/text',
  8. endings: endings });
  9. var reader = new FileReader();
  10. reader.onload = function(event){
  11. console.log(endings + ' of ' + JSON.stringify(string) +
  12. ' => ' + JSON.stringify(reader.result));
  13. };
  14. reader.readAsText(blob);
  15. };
  16.  
  17. testEndings('foo\nbar', 'native');//result is native of "foo\nbar" => "foo\r\nbar"
  18. testEndings('foo\r\nbar', 'native');//result is native of "foo\r\nbar" => "foo\r\nbar"
  19. testEndings('foo\nbar', 'transparent');//result is transparent of "foo\nbar" => "foo\nbar"
  20. 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 ''.

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

BLOB二进制大数据的更多相关文章

  1. postgresql存储二进制大数据文件

    如果想把整个文件或图片存储在数据表的一个字段内,该字段可以选择二进制类型,然后将文件按二进制存储起来,文本文件也可以存在text字段内. 示例如下: 二进制类型bytea的操作(在最大值内,有内存限制 ...

  2. JDBC(5)-处理大数据

    大数据对象处理主要有CLOB(character large object) 和BLOB(binary large object) 两种类型的字段. 在CLOB中可以存储大字符对象,比如长篇小说:在B ...

  3. JavaWeb学习笔记(十四)—— 使用JDBC处理MySQL大数据

    一.什么是大数据 所谓大数据,就是大的字节数据,或大的字符数据.大数据也称之为LOB(Large Objects),LOB又分为:clob和blob,clob用于存储大文本,blob用于存储二进制数据 ...

  4. 处理大数据对象clob数据和blob数据

    直接上下代码: package com.learn.jdbc.chap06; import java.io.File; import java.io.FileInputStream; import j ...

  5. BLOB:大数据,大对象,在数据库中用来存储超长文本的数据,例如图片等

    将一张图片存储在mysql中,并读取出来(BLOB数据:插入BLOB类型的数据必须使用PreparedStatement,因为插入BLOB类型的数据无法使用字符串拼写): -------------- ...

  6. 在HDInsight中从Hadoop的兼容BLOB存储查询大数据的分析

    在HDInsight中从Hadoop的兼容BLOB存储查询大数据的分析 低成本的Blob存储是一个强大的.通用的Hadoop兼容Azure存储解决方式无缝集成HDInsight.通过Hadoop分布式 ...

  7. JDBC 复习3 存取Oracle大数据 clob blob

    1 目录结构记得导包咯 mysql oracle 2 代码,DBUtil工具类见前面的随笔博文 package dbex.mysql; import java.io.BufferedReader; i ...

  8. Java数据库——处理大数据对象

    处理大数据对象 CLOB中可以存储海量文字 BLOB中可以存储海量二进制数据 如果程序中要想处理这样的大对象操作,则必须使用PreparedStatement完成,所有的内容要通过IO流的方式从大文本 ...

  9. 使用JDBC处理MySQL大数据

    一.基本概念 大数据也称之为LOB(Large Objects),LOB又分为:clob和blob,clob用于存储大文本,blob用于存储二进制数据,例如图像.声音.二进制文等. 在实际开发中,有时 ...

随机推荐

  1. filter 中用spring StopWatch 监控请求执行时间

    在filter中用spring stopWatch 来统计每个请求的执行时间: 虽然在firefox 中可以清楚的看到每个请求的执行时间,但是为了测试,记录日志, 方便以后查询维护. 还是必要的,下面 ...

  2. 邁向IT專家成功之路的三十則鐵律 鐵律七:IT人效率之道-時間管理

    彷間有許多與時間管理方面的相關書籍與實務課程,但是究竟對於一位IT專業人士來說,甚麼樣的時間管理法則才是最有效率的呢?過去有許多IT朋友私下請教顧大俠這個問題,而顧大俠始終沒有很完整的分享這方面的經驗 ...

  3. 一道简单DP题

    问题: 给定一个整数的数组,相邻的数不能同时选,求从该数组选取若干整数,使得他们的和最大,要求只能使用o(1)的空间复杂度.要求给出伪码. 解答: int maxSum(vector<int&g ...

  4. G 全然背包

    <span style="color:#3333ff;">/* /* _________________________________________________ ...

  5. 非常不错的ajax原理总结

    在工作中用了Ajax N多次了,也看过一些相关方面的书籍,也算是认识了它,但是一直没有认真总结和整理过相关的东东,失败!近有闲情,将之总结如下:[名称]Ajax是Asynchronous JavaSc ...

  6. Cursor类用法:

      Cursor类用法:   http://www.2cto.com/kf/201109/103163.html   Ctrl+Shift+G 查找类.方法和属性的引用.这是一个非常实用的快捷键,例如 ...

  7. 取消CentOS 的图形界面 开机直接进入命令行模式(转)

    (1)具体操作   #vi /etc/inittab          –编辑/etc/inittab文件 找到下面语句: # Default runlevel. The runlevels used ...

  8. mysql优化之索引建立的规则

    索引经常使用的数据结构为B+树.结构例如以下 如上图,是一颗b+树,关于b+树的定义能够參见B+树,这里仅仅说一些重点.浅蓝色的块我们称之为一个磁盘块,能够看到每一个磁盘块包括几个数据项(深蓝色所看到 ...

  9. Effective Java - [2. 创建与销毁对象]

    让对象的创建与销毁在掌控中. Item 1: 使用静态工厂方法而非使用构造函数 public static Boolean valueOf(boolean b) { return b ? Boolea ...

  10. OcelotAPI 简单使用—服务发现、流控

    我这人比较懒 直接上配置文件的图 其中serviceName是服务名称, LoadBalancer是负载均衡策略. 对于流控我为了做测试写的1s 限制5次请求. 剩下的看名字就OK了. 要使用服务发现 ...