所以我正在创建一个网站。我希望用户能够下载文件。所以我制作了这个脚本
var dwnldBtn = document.getElementById("downloadButton");
var filename = "";
var ext = "";
var title = document.getElementsByTagName("title")[0].innerText.split(" ");
async function FetchTheRest() {
fetch(`https://pathToFile`)
.catch((err) => {
console.log("err");
})
.then((res) => res.blob())
.then((blob) => {
document.body.append(anchor);
anchor.style = "display: none;";
var url = window.URL.createObjectURL(blob);
anchor.href = url;
anchor.download = filename;
dwnldBtn.style = "background-color: #00ff00;";
});
}
async function getEXT() {
var JSON = await fetch("https://pathToFile.json").then((result) => {
return result.json();
});
JSON.versions.forEach((version, index) => {
if (version.version == title[4]) {
ext = version.ext;
}
});
if (ext != "") {
filename = "DSGM " + title[4] + "." + ext;
document.getElementById("NameOfFile").innerHTML = filename;
FetchTheRest();
}
}
getEXT();
var anchor = document.createElement("a");
dwnldBtn.addEventListener("click", function () {
anchor.click();
});
但当我运行这个程序时,它有时会起作用,而其他时候它会给我这些错误:
错误1:
Uncaught (in promise) TypeError: Failed to fetch
Promise.then (async)
FetchTheRest @ downloader.js:12
getEXT @ downloader.js:37
await in getEXT (async)
(anonymous) @ downloader.js:41
错误2:
downloader.js:7 GET https://pathToFile net::ERR_FAILED 200
FetchTheRest @ downloader.js:7
getEXT @ downloader.js:37
await in getEXT (async)
(anonymous) @ downloader.js:41
注意:出现此错误的文件是较大的文件。所以我不知道这是否与此有关。
此外,您将在getEXT函数中看到一个fetch(而不是给出错误的那个(。这个获取是获取一个JSON文件,其中包含所需的信息。比如(文件的(版本号、图像(预览图像(和文本(文件扩展名(。
这对我有效。
fetch(`https://pathToFile`)
.then((response) => {
if (response.ok) {
return response.blob();
}
throw new Error('Something went wrong');
})
.then((blob) => {
document.body.append(anchor);
anchor.style = "display: none;"
var url = window.URL.createObjectURL(blob)
anchor.href = url;
anchor.download = filename;
dwnldBtn.style = "background-color: #00ff00;"
})
.catch((err) => {
console.log(err)
});