使用jquery ajax下载二进制文件 [英] Using jquery ajax to download a binary file
问题描述
我正在尝试使用jquery ajax下载二进制音频文件。
I am attempting to use jquery ajax to download a binary audio file.
通常我会发出如下命令:
Normally i would just issue a command like this:
windows.location.href = 'http://marksdomain(dot)com/audioFile.wav' ;
但是,最近我们的服务器一直等待太长时间才响应,我收到一个令人讨厌的网关超时消息。
However, recently our server has been waiting too long to respond, and I get a nasty gateway timeout message.
有人建议我使用jquery-ajax,这是有道理的,因为那时我可以更好地控制超时。
It has been suggested that i use jquery-ajax instead, which makes sense since then i would have more control over the timeout.
以下是我到目前为止玩过的代码:
Here is the code i have played with so far:
$.ajax(
{ url: 'http://marksdomain(dot)com/audioFile.wav'
, timeout: 999999
, dataType: 'binary'
, processData: false // this one does not seem to do anything ?
, success: function(result) {
console.log(result.length);
}
, error: function(result, errStatus, errorMessage){
console.log(errStatus + ' -- ' + errorMessage);
}
当我省略dataType时,二进制文件的大小比服务器上实际大三倍。但是,当我使dataType等于binary时,ajax会抛出一个错误:
When i omit the "dataType", the binary file is coming through about three times larger than it actually is on the server. However, when i make the dataType equal to "binary", ajax throws an error:
"No conversion from text to binary"
从一些早期帖子中,听起来好像jquery-ajax无法以这种方式处理二进制文件。
From some earlier posts, it sounds as if jquery-ajax cannot handle binary files in this manner.
我确实发现了实际有效的 Delivery.js 我正在努力尝试,但我宁愿不使用节点解决方案。
I did discover Delivery.js which actually works quite well for what I am attempting, but I would rather not use a node solution if possible.
有什么建议吗?
推荐答案
直接使用XHR。此示例来自 MDN :
Just use XHR directly. This example is taken from MDN:
var oReq = new XMLHttpRequest();
oReq.open("GET", "/myfile.png", true);
oReq.responseType = "arraybuffer";
oReq.onload = function(oEvent) {
var arrayBuffer = oReq.response;
// if you want to access the bytes:
var byteArray = new Uint8Array(arrayBuffer);
// ...
// If you want to use the image in your DOM:
var blob = new Blob(arrayBuffer, {type: "image/png"});
var url = URL.createObjectURL(blob);
someImageElement.src = url;
// whatever...
};
oReq.send();
这篇关于使用jquery ajax下载二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!