Decoding a data: URI is basically a two-step job:
- Strip off the
data: header so you’re left with the raw payload.
- Decode that payload (Base-64 or URL-encoded) back into bytes or text.
Below are quick recipes for the most common places you’ll want to do it.
Anatomy refresher
data:<mime-type>[;charset=<enc>][;base64],<payload>
│ │
└─ header ──────────────┘
• If ;base64 is present → the payload is Base-64.
• If not → it’s plain text that’s percent-encoded.
Browser JavaScript (decode → Blob / download)
function dataURItoBlob(dataURI) {
const [header, payload] = dataURI.split(',');
const isBase64 = header.includes(';base64');
const mime = header.match(/data:([^;]+)/)[1];
const byteString = isBase64
? atob(payload) // Base-64 → binary string
: decodeURIComponent(payload); // URL-decode
// binary string → Uint8Array
const bytes = new Uint8Array(byteString.length);
for (let i = 0; i < byteString.length; i++) bytes[i] = byteString.charCodeAt(i);
return new Blob([bytes], { type: mime });
}
// Example: download the file
const blob = dataURItoBlob(myDataURI);
const a = Object.assign(document.createElement('a'), {
href: URL.createObjectURL(blob),
download: 'file' // supply your own filename/extension
});
a.click();
Node.js
const fs = require('fs');
function saveDataURI(dataURI, outPath) {
const [, meta, base64] = dataURI.match(/^data:(.*?);base64,(.*)$/) || [];
if (!base64) throw new Error('Not Base-64 data');
const buf = Buffer.from(base64, 'base64');
fs.writeFileSync(outPath, buf);
}
// usage
saveDataURI(myDataURI, 'output.png');
Python
import base64, mimetypes, re, pathlib
data_uri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUg…'
header, payload = data_uri.split(',', 1)
mime = header.split(';')[0][5:] # strip 'data:'
ext = mimetypes.guess_extension(mime) or ''
path = pathlib.Path('output' + ext)
if ';base64' in header:
binary = base64.b64decode(payload)
else:
binary = bytes(payload, 'utf-8').decode('percent-encode?') # unlikely for binary
path.write_bytes(binary)
print('wrote', path)
Bash / POSIX shell (pure Base-64)
If you already trimmed the header yourself:
echo 'iVBORw0KGgoAAAANSUhEUg...' | base64 -d > image.png
When it’s not Base-64…
Example: data:text/plain,Hello%20world!