READING BINARY DATA USING JQUERY AJAX

http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/

Query is an excellent tool to make web development easy and straightforward. It helps while doing DOM manipulation and makes Ajax requests painless across different browsers and platforms. But if you want make an Ajax request, which is giving binary data as a response, you will discover that it does not work for jQuery, at least for now. Changing “dataType” parameter to “text”, does not help, neither changing it to any other jQuery supported Ajax data type.

Problem here is that jQuery still does not support HTML5 XMLHttpRequest Level 2 binary data type requests – there is even a bug in jQuery bug tracker, which asks for this feature. Although there is a long discussion about this subject on the GitHub, it seems that this feature will not become part of jQuery soon.

To find a solution for this problem, we have to modify XMLHttpRequest itself. To read binary data correctly, we have to treat response type as blob data type.

1
2
3
4
5
6
7
8
9
10
11
12
var xhr = new XMLHttpRequest();
xhr.open('GET', '/my/image/name.png', true);
xhr.responseType = 'blob';
 
xhr.onload = function(e) {
  if (this.status == 200) {
    // get binary data as a response
    var blob = this.response;
  }
};
 
xhr.send();

But what happens if we have to directly modify received binary data? XHR level 2 also introduces  “ArrayBuffer” response type. An ArrayBuffer is a generic fixed-length container for binary data. They are super handy if you need a generalized buffer of raw data, but the real power is that you can create “views” of the underlying data usingJavaScript typed arrays.

1
2
3
4
5
6
7
8
9
10
var xhr = new XMLHttpRequest();
xhr.open('GET', '/my/image/name.png', true);
xhr.responseType = 'arraybuffer';
 
xhr.onload = function(e) {
  // response is unsigned 8 bit integer
  var responseArray = new Uint8Array(this.response);
};
 
xhr.send();

This request creates an unsigned 8-bit integer array from data buffer. ArrayBuffer is especially useful if you have to read data for WebGL project,WebSocket or Canvas 2D

Binary data ajax tranport for jQuery

Sometimes making complete fallback to XMLHttpRequest is not a good idea, especially if you want to keep jQuery code clean and understandable. To solve this problem, jQuery allows us to create Ajax transports – plugins, which are created to make custom Ajax requests.

Our idea is to make “binary” Ajax transport based on our previous example. This Ajax transport creates new XMLHttpRequest and passes all the received data back to the jQuery.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
*
* jquery.binarytransport.js
*
* @description. jQuery ajax transport for making binary data type requests.
* @version 1.0
* @author Henry Algus <henryalgus@gmail.com>
*
*/
 
// use this transport for "binary" data type
$.ajaxTransport("+binary", function(options, originalOptions, jqXHR){
    // check for conditions and support for blob / arraybuffer response type
    if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob)))))
    {
        return {
            // create new XMLHttpRequest
            send: function(headers, callback){
// setup all variables
                var xhr = new XMLHttpRequest(),
url = options.url,
type = options.type,
async = options.async || true,
// blob or arraybuffer. Default is blob
dataType = options.responseType || "blob",
data = options.data || null,
username = options.username || null,
password = options.password || null;
                xhr.addEventListener('load', function(){
var data = {};
data[options.dataType] = xhr.response;
// make callback and send data
callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
                });
 
                xhr.open(type, url, async, username, password);
// setup custom headers
for (var i in headers ) {
xhr.setRequestHeader(i, headers[i] );
}
                xhr.responseType = dataType;
                xhr.send(data);
            },
            abort: function(){
                jqXHR.abort();
            }
        };
    }
});

For this script to work correctly, processData must be set to false, otherwise jQuery will try to convert received data into string, but fails.

Now it is possible to read binary data using usual jQuery syntax:

1
2
3
4
5
6
7
8
9
$.ajax({
  url: "/my/image/name.png",
  type: "GET",
  dataType: "binary",
  processData: false,
  success: function(result){
  // do something with binary data
  }
});

If you want receive ArrayBuffer as response type, you can use responseType parameter while creating Ajax request:

1
responseType:'arraybuffer'

How to setup custom headers?

It is possible to set multiple custom headers when you are making the request. To set custom headers, you can use “header” parameter and set its value as an object, which has list of headers:

1
2
3
4
5
6
7
8
9
10
$.ajax({
          url: "image.png",
          type: "GET",
          dataType: 'binary',
          headers:{'Content-Type':'image/png','X-Requested-With':'XMLHttpRequest'},
          processData: false,
          success: function(result){
          }
});
 

Another options

Asynchronous or synchronous execution

It is possible to change execution type from asynchronous to synchrous when setting parameter “async” to false.

async:false,

Login with user name and password

If your script needs to have authentication during the request, you can use username and password parameters.

username:'john', password:'smith',

Supported browsers

BinaryTransport requires XHR2 responseType, ArrayBuffer and Blob response type support from your browser, otherwise it does not work as expected. Currently most major browsers should work fine.

Firefox: 13.0+ Chrome: 20+ Internet Explorer: 10.0+ Safari: 6.0 Opera: 12.10

Binary transport jQuery plugin is also available in myGitHub repository.

使用jQuery AJAX读取二进制数据的更多相关文章

  1. jQuery ajax读取本地json文件

    jQuery ajax读取本地json文件 json文件 { "first":[ {"name":"张三","sex": ...

  2. SQLite数据库如何存储和读取二进制数据

    SQLite数据库如何存储和读取二进制数据 1. 存储二进制数据 SQLite提供的绑定二进制参数接口函数为: int sqlite3_bind_blob(sqlite3_stmt*, int, co ...

  3. jquery ajax返回json数据进行前后台交互实例

    jquery ajax返回json数据进行前后台交互实例 利用jquery中的ajax提交数据然后由网站后台来根据我们提交的数据返回json格式的数据,下面我来演示一个实例. 先我们看演示代码 代码如 ...

  4. 练习 jquery+Ajax+Json 绑定数据 分类: asp.net 练习 jquery+Ajax+Json 绑定数据 分类: asp.net

    练习 jquery+Ajax+Json 绑定数据

  5. python 读取二进制数据到可变缓冲区中

    想直接读取二进制数据到一个可变缓冲区中,而不需要做任何的中间复制操作.或者你想原地修改数据并将它写回到一个文件中去. 为了读取数据到一个可变数组中,使用文件对象的readinto() 方法.比如 im ...

  6. js进阶ajax读取json数据(ajax读取json和读取普通文本,和获取服务器返回数据(链接)都是一样的,在url处放上json文件的地址即可)

    js进阶ajax读取json数据(ajax读取json和读取普通文本,和获取服务器返回数据(链接)都是一样的,在url处放上json文件的地址即可) 一.总结 ajax读取json和读取普通文本,和获 ...

  7. (第二章第三部分)TensorFlow框架之读取二进制数据

    系列博客链接: (第二章第一部分)TensorFlow框架之文件读取流程:https://www.cnblogs.com/kongweisi/p/11050302.html (第二章第二部分)Tens ...

  8. Jquery Ajax 提交json数据

    在MVC控制器(这里是TestController)下有一个CreateOrder的Action方法 [HttpPost] public ActionResult CreateOrder(List&l ...

  9. ajax读取json数据

    首先建立json.txt文件 { "programmers": [ { "firstName": "Brett", "lastNa ...

随机推荐

  1. [ZJOI 2012]灾难

    Description 阿米巴是小强的好朋友. 阿米巴和小强在草原上捉蚂蚱.小强突然想,果蚂蚱被他们捉灭绝了,那么吃蚂蚱的小鸟就会饿死,而捕食小鸟的猛禽也会跟着灭绝,从而引发一系列的生态灾难. 学过生 ...

  2. [ZJOI2010]排列计数

    题目描述 称一个1,2,...,N的排列P1,P2...,Pn是Magic的,当且仅当2<=i<=N时,Pi>Pi/2. 计算1,2,...N的排列中有多少是Magic的,答案可能很 ...

  3. bzoj 4545: DQS的trie

    Description DQS的自家阳台上种着一棵颗粒饱满.颜色纯正的trie. DQS的trie非常的奇特,它初始有n0个节点,n0-1条边,每条边上有一个字符.并且,它拥有极强的生长力:某个i时刻 ...

  4. [BZOJ]2594 水管局长数据加强版(Wc2006)

    失踪人口回归. LCT一直是小C的弱项,特别是这种维护链的信息的,写挂了就会调代码调到心态爆炸. 不过还好这一次的模板练习没有出现太多的意外. Description SC省MY市有着庞大的地下水管网 ...

  5. WebStorm配置node.js调试

    最近因为工作关系,一直在做node.js的开发,学习了koa框架,orm框架sequelize,以及swagger文档的配置.但是,最近因为swagger文档使用了es6的修饰器那么个东西(在java ...

  6. day4 liaoxuefeng---函数式编程

    一.概述: 函数式编程的一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数! Python对函数式编程提供部分支持.由于Python允许使用变量,因此,Python不是纯函数式编程 ...

  7. c语言第二次作业2

    ---恢复内容开始--- (一)改错题 1.输出带框文字:在屏幕上输出以下3行信息. 源程序 对源程序进行编译 错误信息1: 错误原因:stdio.h输入错误 改正方法:i和d互换位置 错误信息2: ...

  8. RESTful 最佳实战

    在GitHub上看到一本不错的关于REST实战的书,很高兴分享阅读笔记.[下载地址] 一.什么是REST(WHAT) REST架构描述了六种约束.(统一接口.无状态.可缓存.CS架构.分层系统.按需编 ...

  9. 使用JdbcTemplate 操作PostgreSQL,当where条件中有timestamp类型时,报错operator does not exist: timestamp w/out timezone

    今天遇到一个问题,找了还半天,Google一下,官网显示是一个bug. 思考一番肯定是类型出了问题. Controller: Service:转化时间戳 Dao: 一波转换搞定!

  10. MySQL Innodb如何找出阻塞事务源头SQL

    在MySQL数据库中出现了阻塞问题,如何快速查找定位问题根源?在实验开始前,我们先梳理一下有什么工具或命令查看MySQL的阻塞,另外,我们也要一一对比其优劣,因为有些命令可能在实际环境下可能并不适用. ...