How Browser Blob URLs Make File Downloads Work
ملخص
Pixel shares a clear guide to browser file downloads using JavaScript Blobs and temporary object URLs. It explains how to fetch CSV data as a blob, label it with the text/csv MIME type, create a URL, and save it with an anchor element—helpful details for building reliable exports and preventing corrupted files.
DEV Community
What's a "Blob"? How Browsers Download Files
When you implement a CSV download feature, you run into unfamiliar code like this. const blob = new Blob([response.data], { type: 'text/csv' })
const objectURL = window.URL.createObjectURL(blob)
downloadFile(objectURL, 'data.csv')
"Blob?" "Create a URL?" "Then download it? From where?" This post will clear all that up. What's a Blob? Blob = a "chunk of data" that can hold anything. To the browser, it's "something like a file." It can hold text, images, CSV, PDF, whatever, and it can carry a type label (MIME type) like "this is CSV." To tell the browser "this is a file, please save it," you need to turn the data into "file form" = a Blob. Left as raw text data, it's just treated as a plain string. The letter analogy Letter analogy The real thing The document (the CSV contents) response.data Putting it in an envelope new Blob(...) Sticking on an address label The URL from createObjectURL Mailing it = saving Clicking What the code means // ① Receive it as binary (forget this and your CSV can get corrupted)
const response = await api.get(url, { responseType: 'blob' })
// ② Put the data into a "CSV file" box
const blob = new Blob([response.data], { type: 'text/csv' })
// ③ Issue a temporary URL that points to that box
const objectURL = window.URL.createObjectURL(blob)
// ④ Have that URL saved as a file
downloadFile(objectURL, 'data.csv')
The key is the URL in ③. It's not a location on a server like https://...; it's a label pointing to data you already have on hand (in the browser's memory). What's inside downloadFile is simple too: "just create an with a download attribute and click it with JS." function downloadFile(url, filename) {
const a = document.createElement('a')
a.href = url
a.download = filename
a.click()
}
Since the link points to a blob: URL, it doesn't go to the server; it saves the data you have on hand straight to a file. So even though we say "download the URL," it's not re-downloading anything; it's just saving data you already have. Extra: clean up URLs when you're done A URL from createObjectURL keeps holding onto memory, so it's good manners to release it when you're done. window.URL.revokeObjectURL(objectURL)
Summary Blob = to the browser, "a file-like chunk of data" The URL from createObjectURL is a label pointing to data on hand, not to a server Clicking saves that data as a file This flow is the same for any file: images, PDFs, ZIPs, and so on

Powered by Readybot.io