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. ●HDU 3689 Infinite monkey theorem

    题链: http://acm.hdu.edu.cn/showproblem.php?pid=3689题解: KMP,概率dp (字符串都从1位置开始) 首先对模式串S建立next数组. 定义dp[i] ...

  2. 【BZOJ1483】【HNOI2009】梦幻布丁

    题意:n个连续的点,有若干种颜色,每个颜色会因为某些操作变为另一种颜色,动态查询颜色段数. 解题思路:对每个颜色开一棵平衡树启发式合并应该是最裸的想法,但是我们有更优的! 考虑对每个颜色利用链表储存它 ...

  3. [bzoj4161]Shlw loves matrix I

    来自FallDream的博客,未经允许,请勿转载,谢谢. 给定数列 {hn}前k项,其后每一项满足 hn = a1*h(n-1) + a2*h(n-2) + ... + ak*h(n-k) 其中 a1 ...

  4. Fashion-MNIST:A MNIST-like fashion product database. Benchmark

    Zalando的文章图像的一个数据集包括一个训练集6万个例子和一个10,000个例子的测试集. 每个示例是一个28x28灰度图像,与10个类别的标签相关联. 时尚MNIST旨在作为用于基准机器学习算法 ...

  5. 光电转研发:和计算机没有一点关系的专业怎么去bat类的公司

    光电 女 其实编码能力一般般,拿到百度腾讯研发offer. 一来幸运,二来真的想说行动决定了结果.研一没事就出去家教充实自己赚点钱,研二就开始找实习,去了网易,海康威视,百度实习.感觉还是吃了不少苦的 ...

  6. 详解Tomcat配置JVM参数步骤

    这里向大家描述一下如何使用Tomcat配置JVM参数,Tomcat本身不能直接在计算机上运行,需要依赖于硬件基础之上的操作系统和一个Java虚拟机.您可以选择自己的需要选择不同的操作系统和对应的JDK ...

  7. supervisor使用,配置和安装(包括监控守护进程httpd,keepalived)

    yum -y install supervisor(如果安装不成功,需要更新源,yum -y install epel) 或者: wget --no-check-certificate https:/ ...

  8. django.db.utils.ProgrammingError: 1146 的解决办法

    在models中设置完数据库相关的东西后执行命令 python manage.py makemigrations 此处无错误 再次执行 python manage.py migrate 发生报错 错误 ...

  9. Deap Learning (吴恩达) 第一章深度学习概论 学习笔记

    Deap Learning(Ng) 学习笔记 author: 相忠良(Zhong-Liang Xiang) start from: Sep. 8st, 2017 1 深度学习概论 打字太麻烦了,索性在 ...

  10. 628. Maximum Product of Three Numbers

    Given an integer array, find three numbers whose product is maximum and output the maximum product. ...