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 <a download> |
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 <a> 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
createObjectURLis a label pointing to data on hand, not to a server - Clicking
<a download>saves that data as a file - This flow is the same for any file: images, PDFs, ZIPs, and so on
