đź“„ Download Files via AJAX
Fetch JSON is common. What about images? PDFs? ZIPs? Blob responses handle binary data. Create download links dynamically.
📝 Download Image
async function downloadImage(url) {
const response = await fetch(url);
const blob = await response.blob();
const imageUrl = URL.createObjectURL(blob);
const img = document.createElement('img');
img.src = imageUrl;
document.body.appendChild(img);
// Clean up
URL.revokeObjectURL(imageUrl);
}
// Download and save as file
async function saveFile(url, filename) {
const response = await fetch(url);
const blob = await response.blob();
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
URL.revokeObjectURL(link.href);
}
🎯 PDF and ZIP Generation
// Generate PDF from HTML (server-side)
const response = await fetch('/api/generate-pdf', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ html: content })
});
const pdfBlob = await response.blob();
const pdfUrl = URL.createObjectURL(pdfBlob);
window.open(pdfUrl);
// ZIP file download
async function downloadZip(files) {
const response = await fetch('/api/create-zip', {
method: 'POST',
body: JSON.stringify({ files })
});
const zipBlob = await response.blob();
const url = URL.createObjectURL(zipBlob);
const a = document.createElement('a');
a.href = url;
a.download = 'archive.zip';
a.click();
URL.revokeObjectURL(url);
}
đź’ˇ Blob Types
- image/png, image/jpeg, image/webp
- application/pdf
- application/zip
- text/plain, text/csv
- audio/mpeg, video/mp4
“Server generates PDF reports. Fetch blob, create download link. No page reload, no server temporary files. Blob API is perfect for file downloads.”
