<button onclick="downloadFile('https://httpbin.org/json', 'jsonFile.json' )">Download Single File</button>
<button onclick="downloadMultipleFiles()">Download Multiple Files</button>
function saveFile(url, filename) {
const a = document.createElement("a");
a.href = url;
a.download = filename || "file-name";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
async function downloadFile(url, filename) {
try {
const response = await fetch(url, {
headers: {
Accept:
"application/json, text/plain,application/zip, image/png, image/jpeg, image/*"
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const blob = await response.blob();
const blobUrl = URL.createObjectURL(blob);
saveFile(blobUrl, filename);
URL.revokeObjectURL(blobUrl);
} catch (err) {
console.error("Error in fetching and downloading file:", err);
}
}
async function downloadMultipleFiles() {
const zip = new JSZip();
const file1 = new Blob(["Hello, file 1!"], { type: "text/plain" });
const file2 = new Blob(["Hello, file 2!"], { type: "text/plain" });
zip.file("file1.txt", file1);
zip.file("file2.txt", file2);
const content = await zip.generateAsync({ type: "blob" });
const contentUrl = URL.createObjectURL(content);
saveFile(contentUrl, "zipContent.zip");
}
This Pen doesn't use any external CSS resources.