Skip to content

Download Files

This lesson explains Download Files with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 Download Files API Overview

HTML5 provides several ways to download files in the browser using native HTML and JavaScript. Developers can download existing files using the download attribute, generate files dynamically using the Blob API, download server files using the Fetch API, and create object URLs with URL.createObjectURL().

File downloads are commonly used for exporting CSV reports, downloading PDFs, saving generated JSON, exporting images, creating text files, downloading invoices, saving canvas output, and building browser-based productivity tools.

Download Method Description
HTML download Attribute Downloads an existing file using a normal anchor link.
Blob API Creates file-like data in memory for download.
Object URL Creates a temporary browser URL for a Blob or File.
Fetch API Downloads server files and converts responses into Blob data.
Canvas Export Downloads generated canvas graphics as image files.
File System Access API Saves files directly with user permission in supported browsers.

Basic Download File Example

<a
  href="/files/report.pdf"
  download="monthly-report.pdf">
  Download Report
</a>

The download attribute tells the browser to download the linked file instead of navigating to it. The attribute value can suggest a custom file name.

HTML5 File Download Methods

Different download techniques are useful for different scenarios. Static files can use the download attribute, while dynamic files usually require Blob and object URLs.

Method Best For Example Syntax
Anchor Download Existing files such as PDFs, images, and ZIP files. <a href="/file.pdf" download>
Blob Download Generated text, CSV, JSON, XML, or HTML files. new Blob([content], { type: "text/plain" })
Object URL Temporary download link for Blob or File data. URL.createObjectURL(blob)
Fetch Download Protected or API-generated files from a server. fetch("/api/report").then((res) => res.blob())
Canvas Download Generated charts, drawings, certificates, or images. canvas.toBlob(callback)
File System Access Save files to disk in supported Chromium browsers. window.showSaveFilePicker()

Download a Text File

// Create and download a text file

const content = "Hello from HTML5 Download Files API";

const blob = new Blob(
  [content],
  { type: "text/plain" }
);

const url = URL.createObjectURL(blob);

const link = document.createElement("a");
link.href = url;
link.download = "message.txt";
link.click();

URL.revokeObjectURL(url);

This example creates a text file in memory using Blob, generates a temporary object URL, triggers a download, and then releases the URL to prevent memory leaks.

Download a JSON File

// Create and download JSON file

const user = {
  name: "Ayaan",
  role: "Student",
  active: true
};

const json = JSON.stringify(
  user,
  null,
  2
);

const blob = new Blob(
  [json],
  { type: "application/json" }
);

const url = URL.createObjectURL(blob);

const link = document.createElement("a");
link.href = url;
link.download = "user.json";
link.click();

URL.revokeObjectURL(url);

JSON downloads are useful for exporting configuration files, user data, application state, backup files, and structured API data.

Download a CSV File

// Create and download CSV file

const rows = [
  ["Name", "Role", "Active"],
  ["Ayaan", "Student", "Yes"],
  ["Sita", "Developer", "Yes"]
];

const csv = rows
  .map((row) => row.join(","))
  .join("\n");

const blob = new Blob(
  [csv],
  { type: "text/csv" }
);

const url = URL.createObjectURL(blob);

const link = document.createElement("a");
link.href = url;
link.download = "users.csv";
link.click();

URL.revokeObjectURL(url);

CSV downloads are commonly used for reports, dashboards, tables, analytics exports, invoices, and spreadsheet-compatible data.

Download File from Server Using Fetch

// Download server file using Fetch

async function downloadReport() {
  try {
    const response = await fetch("/api/reports/monthly");

    if (!response.ok) {
      throw new Error("Download failed");
    }

    const blob = await response.blob();
    const url = URL.createObjectURL(blob);

    const link = document.createElement("a");
    link.href = url;
    link.download = "monthly-report.pdf";
    link.click();

    URL.revokeObjectURL(url);
  } catch (error) {
    console.error(error.message);
  }
}

downloadReport();

Fetch-based downloads are useful when files are generated by an API, protected by authentication, or returned dynamically from the server.

Download Canvas as Image

// Download canvas drawing as PNG

const canvas = document.querySelector("#myCanvas");

canvas.toBlob((blob) => {
  if (!blob) {
    return;
  }

  const url = URL.createObjectURL(blob);

  const link = document.createElement("a");
  link.href = url;
  link.download = "canvas-image.png";
  link.click();

  URL.revokeObjectURL(url);
}, "image/png");

Canvas downloads are useful for exporting charts, drawings, image edits, signatures, certificates, and generated graphics.

Save File with File System Access API

// Save file using File System Access API

async function saveTextFile() {
  if (!("showSaveFilePicker" in window)) {
    console.log("File System Access API is not supported.");
    return;
  }

  const handle = await window.showSaveFilePicker(
    {
      suggestedName: "notes.txt",
      types: [
        {
          description: "Text Files",
          accept: {
            "text/plain": [".txt"]
          }
        }
      ]
    }
  );

  const writable = await handle.createWritable();

  await writable.write("Saved from the browser.");
  await writable.close();
}

The File System Access API allows supported browsers to save files directly with user permission. Always provide a fallback download method for unsupported browsers.

Common Download File Types

File Type MIME Type Common Use
Text text/plain Notes, logs, plain text exports.
CSV text/csv Reports, spreadsheets, analytics exports.
JSON application/json Configuration, backups, API data.
HTML text/html Generated pages, templates, documents.
PDF application/pdf Invoices, reports, documents.
PNG image/png Canvas exports, screenshots, graphics.
JPEG image/jpeg Photos and compressed image exports.
ZIP application/zip Compressed file bundles.

Download Files Best Practices

  • Use the download attribute for simple static files.
  • Use Blob and object URLs for dynamically generated files.
  • Set the correct MIME type for every generated file.
  • Use clear and safe file names with proper extensions.
  • Call URL.revokeObjectURL() after downloads to prevent memory leaks.
  • Handle Fetch errors and failed downloads gracefully.
  • Provide loading and success messages for large downloads.
  • Offer fallback downloads when advanced APIs are unsupported.

Common Download File Mistakes

  • Forgetting to revoke object URLs after downloading.
  • Using the wrong MIME type for generated files.
  • Creating downloads without user interaction where browsers may block them.
  • Not handling failed Fetch requests.
  • Using unsafe or unclear file names.
  • Trying to save files directly without checking browser support.
  • Generating very large files fully in memory without warning users.
  • Not providing accessible status messages for download actions.

Key Takeaways

  • HTML5 supports file downloads using links, Blob, Fetch, Canvas, and browser APIs.
  • The download attribute is best for simple existing files.
  • Blob downloads are ideal for generated text, CSV, JSON, and binary files.
  • Fetch can download protected or API-generated server files.
  • Canvas can export drawings and charts as image files.
  • Always handle browser support, memory cleanup, accessibility, and error states.

Pro Tip

For most dynamic downloads, use this pattern: Create Blob → Create Object URL → Trigger Download → Revoke URL. This approach works well for CSV, JSON, text, images, generated reports, and many browser-based export features.