不幸的是,@BrianFreud 的回答不符合我的需要,我有一点不同的需要,我知道这不是@BrianFreud 问题的答案,但我把它留在这里是因为很多人都和我一样需要。我需要诸如“如何从 URL 获取文件或 blob?”之类的内容,而当前的正确答案不符合我的需要,因为它不是跨域的。
我有一个使用 Amazon S3/Azure 存储中的图像的网站,并在那里存储使用唯一标识符命名的对象:
示例:http://****.blob.core.windows.net/systemimages/bf142dc9-0185-4aee-a3f4-1e5e95a09bcf
其中一些图像应从我们的系统界面下载。
为了避免通过我的 HTTP 服务器传递这个流量,因为这个对象不需要任何安全性来访问(通过域过滤除外),我决定在用户的浏览器上发出直接请求并使用本地处理来给文件一个真实的名称和扩展名。
为了实现这一点,我使用了 Henry Algus 的这篇精彩文章:
http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
1.第一步:为jquery添加二进制支持
/**
*
* 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();
}
};
}
});
2。第二步:使用此传输类型发出请求。
function downloadArt(url)
{
$.ajax(url, {
dataType: "binary",
processData: false
}).done(function (data) {
// just my logic to name/create files
var filename = url.substr(url.lastIndexOf('/') + 1) + '.png';
var blob = new Blob([data], { type: 'image/png' });
saveAs(blob, filename);
});
}
现在您可以随意使用创建的 Blob,在我的情况下,我想将其保存到磁盘。
3.可选:使用 FileSaver 将文件保存在用户的计算机上
我已经使用 FileSaver.js 将下载的文件保存到磁盘,如果您需要这样做,请使用这个 javascript 库:
https://github.com/eligrey/FileSaver.js/
我希望这可以帮助其他有更具体需求的人。