So I am creating a website. And I want the user to be able to download files. And so I made this script
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();
});
But when I run this, it sometimes works, and other times it gives me these errors:
Error 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
Error 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
NOTE: the files that I get this error on are bigger files. So I don't know if that has anything to do with it.
Also you will see in the getEXT function, there is a fetch (not the one giving errors). This fetch is getting a JSON file with needed information in it. Like the version number (of file), image (preview image), and ext (the file extension).