不幸的是,@ BrianFreud的答案不符合我的需求,我有一点不同的需求,我知道这不是@BrianFreud的问题的答案,但是我将它留在这里因为很多人带着我的同样需要来到这里 . 我需要“如何从URL获取文件或blob?”这样的内容,并且当前正确的答案不符合我的需求,因为它不是跨域的 .
我有一个网站,它使用来自Amazon S3 / Azure存储的图像,并在那里存储以uniqueidentifiers命名的对象:
sample: http://****.blob.core.windows.net/systemimages/bf142dc9-0185-4aee-a3f4-1e5e95a09bcf
其中一些图像应该从我们的系统界面下载 . 为了避免通过我的HTTP服务器传递此流量,因为此对象不需要访问任何安全性(除了域过滤),我决定在用户的浏览器上直接请求并使用本地处理为文件提供真实姓名和延期 .
1. First step: Add binary support to jquery
/**
*
* jquery.binarytransport.js
*
* @description. jQuery ajax transport for making binary data type requests.
* @version 1.0
* @author Henry Algus
*
*/
// 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. Second step: Make a request using this transport type.
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. Optional: Save file on user's computer using FileSaver
我已经使用FileSaver.js将下载的文件保存到磁盘,如果你需要完成它,请使用这个javascript库:
我希望这可以帮助其他更具体需求的人 .