jQuery Ajax-下载不完整的(二进制)文件 [英] jQuery Ajax - downloading incomplete (binary) file

查看:93
本文介绍了jQuery Ajax-下载不完整的(二进制)文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我所拥有的:

jquery/1.10.2

$.ajax({
    url: "http://samplepdf.com/sample.pdf",
    dataType: "text",
    data: "",
    success: function(data) {
        alert(data.length);
    },
    error: function(a, b, c) {}
});

当我在本地运行(在OS X上的Safari 6.0.5中)时,得到211300.但是,实际文件似乎为218882字节.使用完全ASCII的内容(例如 http://www.angio.net/pi/digits/pi1000000.txt ),它似乎可以正常工作.

When I run that locally (in Safari 6.0.5 on OS X), I get 211300. However, the actual file appears to be 218882 bytes. With something fully ASCII (such as http://www.angio.net/pi/digits/pi1000000.txt), it seems to work correctly.

我不需要下载文件,而是使用它的内容.

I don't need to download the file, but rather, work with its content.

有什么方法可以使ajax与二进制文件(客户端或服务器端)一起工作,而无需使用base64?

Is there any way to make ajax work with binary files (either client side or server side) without resorting to using base64?

推荐答案

我认为您需要使用类型化的数组. Javascript处理二进制文件的方式. 没有其他方法可以处理纯二进制数据.但是使用类型化数组,您几乎可以在其他任何地方使用二进制文件进行所有操作.

I think you need to use typed arrays. Javascript way of dealing with binary. There is no other way to deal with pure binary data. But with typed arrays you can do almost everything that you would want to do with binary anywhere else.

var myArray = new ArrayBuffer(512);
var longInt8View = new Uint8Array(myArray);

for (var i=0; i< longInt8View.length; i++) {
  longInt8View[i] = i % 255;
}

var xhr = new XMLHttpRequest;
xhr.open("POST", url, false);
xhr.send(myArray);

接收类型化数组

两种方法... 第一

var oReq = new XMLHttpRequest();
oReq.open("GET", "/myfile.png", true);
oReq.responseType = "arraybuffer";

oReq.onload = function (oEvent) {
  var arrayBuffer = oReq.response; // Note: not oReq.responseText
  if (arrayBuffer) {
    var byteArray = new Uint8Array(arrayBuffer);
    for (var i = 0; i < byteArray.byteLength; i++) {
      // do something with each byte in the array
    }
  }
};

oReq.send(null);

第二

var oReq = new XMLHttpRequest();
oReq.open("GET", "/myfile.png", true);
oReq.responseType = "arraybuffer";

oReq.onload = function(oEvent) {
  var blob = new Blob([oReq.response], {type: "image/png"});
  // ...
};

oReq.send();

来源: https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

发送: $.ajax(url,{data:myArray});

接收中:未经测试...

$.ajax('https://dl.dropboxusercontent.com/u/139992952/coffee.png',{
    contentType: "arraybuffer",
    success: function(d){
        var blob = new Blob([d], {type: "image/png"}),
            u = URL.createObjectURL(blob);
    }
});

这篇关于jQuery Ajax-下载不完整的(二进制)文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆