To download a file from a URL or API in the browser, use fetch() + Blob + URL.createObjectURL() with a temporary <a download> link when you need custom headers (like Authorization tokens) or API-generated binary/text responses, or use a direct <a href="..." download> link for public static files. With jQuery, use $ to select elements and attach the "click" handler while delegating the file retrieval and Blob download to standard browser APIs.
1. Downloading Authenticated or API-Generated Files with fetch() and Blob
When an endpoint requires auth headers, query/body parameters, or returns a dynamically generated file (CSV, PDF, JSON, ZIP), fetch it with fetch(), convert the body into a Blob, generate a temporary blob: URL via URL.createObjectURL(blob), trigger a click on a temporary <a download> element, and revoke the object URL in a finally block:
// Download a file from a URL or API with optional headers using fetch() and Blob
async function downloadFileFromApi(url, fileName = "download", headers = {}) {
if (typeof url !== "string" || url.trim() === "") {
return;
}
const response = await fetch(url, {
method: "GET",
headers
});
if (!response.ok) {
throw new Error(`Download failed with HTTP ${response.status}`);
}
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
try {
const anchor = document.createElement("a");
anchor.href = objectUrl;
anchor.download = fileName;
anchor.style.display = "none";
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
} finally {
URL.revokeObjectURL(objectUrl);
}
}
// Example usage with an Authorization header:
// downloadFileFromApi("/api/exports/orders.csv", "orders.csv", { Authorization: "Bearer TOKEN" });
- Supports headers and status checks: Lets you attach bearer tokens or inspect
response.okbefore saving a file. - Guaranteed URL cleanup:
URL.revokeObjectURL(objectUrl)insidefinallyfrees memory even if an error occurs after creating the URL.
2. Triggering the Download from a jQuery Event Handler
jQuery does not include a built-in binary file-download helper, so use jQuery for DOM selection and event binding ($(selector).on("click", ...)) and invoke the fetch() + Blob downloader cleanly:
// Bind a download button via jQuery and delegate binary fetching to fetch() + Blob
function bindJQueryDownload(selector, resolveOptions) {
if (typeof window.jQuery !== "function" || typeof resolveOptions !== "function") {
return;
}
window.jQuery(selector).on("click", async (event) => {
event.preventDefault();
const options = resolveOptions(event.currentTarget);
if (!options || !options.url) {
return;
}
try {
await downloadFileFromApi(options.url, options.fileName || "download", options.headers || {});
} catch (error) {
console.error("Failed to download file:", error);
}
});
}
// Example usage:
// bindJQueryDownload("#download-report-btn", (btn) => ({
// url: btn.dataset.downloadUrl,
// fileName: btn.dataset.fileName || "report.pdf"
// }));
- Clear separation of concerns: jQuery handles event binding cleanly while
fetch()andBlobhandle binary data without corruption. - Non-mutating options lookup: Reads configuration from
resolveOptions(event.currentTarget)without mutating input objects or DOM nodes.
3. Common Traps to Avoid
Downloading files from URLs or APIs with JavaScript and jQuery commonly runs into a few pitfalls:
- Using
$.ajax()or$.get()for binary files: jQuery Ajax defaults to text/JSON/XML parsing and can corrupt binary streams (PDF,ZIP, images)—usefetch()with.blob()instead. - Expecting
anchor.downloadto force a filename across different origins: Cross-origin URLs without matchingContent-Disposition: attachmentheaders and CORS permissions may open in the browser rather than saving with the customdownloadname. - Forgetting
URL.revokeObjectURL(): Leaving createdblob:URLs unrevoked keeps binary data in memory longer than needed.
TL;DR: Use fetch() + response.blob() + URL.createObjectURL() with a temporary <a download> click (and URL.revokeObjectURL() cleanup) for API or authenticated downloads, and use jQuery to bind the click event.
