我正在尝试给自己写一个小帮手来下载一些Chromecast背景,因为照片很棒。我的代码如下:
<html>
<head>
<script type="text/javascript">
function downloadFiles() {
var backgroundsJSON = [
{
"url": "https://lh6.googleusercontent.com/-A0tXm8gjfMU/U08VDMRGtuI/AAAAAAAAvrI/IQEscTGZyJY/s1920-w1920-h1080-c/IMG_0293%2Bhe.jpg",
"author": "Ziv Horesh"
},
{
"url": "https://lh6.googleusercontent.com/-3LiF-MBl6OE/UO5TXZ724aI/AAAAAAAAE50/JWLqdeEM9QY/s1920-w1920-h1080-c/Colorado%2BRiver%2BSunset.jpg",
"author": "Romain Guy"
},
{
"url": "https://lh4.googleusercontent.com/-wkrGBuk0DoA/Us9JnUoXnTI/AAAAAAAAkTA/yDQexzLKhKY/s1920-w1920-h1080-c/DSC_0660.JPG",
"author": "Alistair Nicol"
},
{
"url": "https://lh3.googleusercontent.com/-1xZqgaRDIec/Tg1dMJq1vBI/AAAAAAAAALc/7m0Tpv2htVc/s1920-w1920-h1080-c/071227-4144-PtLomaReef.jpg",
"author": "Patrick Smith"
},
{
"url": "https://lh3.googleusercontent.com/-36YdSRh6q9w/TgtZEChvrkI/AAAAAAAJA0M/zVvIUAdwQ3Q/s1920-w1920-h1080-c/976865336_a%2Bview%2Bof%2Bqueenstown.jpg",
"author": "Trey Ratcliff"
}
]
for (i = 0; i < backgroundsJSON.length; i++) {
var url = backgroundsJSON[i].url;
// Get file name from url.
var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
a.download = filename; // Set the file name.
a.style.display = 'none';
document.body.appendChild(a);
a.click();
delete a;
};
xhr.open('GET', url);
xhr.send();
}
}
</script>
</head>
<body>
<input id="clickMe" type="button" value="Down Load ChromeCastBackgrounds" onclick="downloadFiles();" />
</body>
</html>
然而,当我点击html页面上的按钮时 - 最终图像下载了4次,而不是我希望的4张独特图像?
答案 0 :(得分:0)
有这个工作
function SaveToDisk(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
save.download = fileName || fileURL;
var evt = document.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0,
false, false, false, false, 0, null);
save.dispatchEvent(evt);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
// for IE
else if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, "_blank");
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
}
for (i = 0; i < backgroundsJSON.length; i++) {
var url = backgroundsJSON[i].url;
// Get file name from url.
var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
SaveToDisk(url, filename);
}
答案 1 :(得分:-1)
您需要设置异步true;
更改
xhr.open('GET', url);
到
xhr.open('GET', url, true);