<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");
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js
  2. https://cdnjs.cloudflare.com/ajax/libs/redux/4.1.1/redux.min.js
  3. https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js