fetchToBase64
Category: File Operations
Namespace: web.files.fetchToBase64
Description
Fetch files from URLs and return as base64-encoded strings. This API is ideal for loading remote content into memory for display, processing, or creating data URLs.
Syntax
// Simple form
const base64 = await web.files.fetchToBase64(url);
// Options form
const base64 = await web.files.fetchToBase64({
url: string,
timeout: number
});
Parameters
- url (required) - HTTP/HTTPS URL to fetch from
- timeout (optional) - Timeout in milliseconds (default: 30000)
Returns
Promise<string> - Base64-encoded file content
Example
// Display remote image
const base64 = await web.files.fetchToBase64('https://example.com/logo.png');
const img = document.createElement('img');
img.src = `data:image/png;base64,${base64}`;
document.body.appendChild(img);
// With custom timeout
const base64 = await web.files.fetchToBase64({
url: 'https://example.com/large-image.jpg',
timeout: 60000 // 60 seconds for large files
});
// Create data URL for CSS
const base64 = await web.files.fetchToBase64('https://example.com/bg.jpg');
document.body.style.backgroundImage = `url(data:image/jpeg;base64,${base64})`;
Use Cases
- Display remote images without saving to disk
- Load remote data for in-memory processing
- Create data URLs for CSS/HTML
- Fetch small files for immediate use
- Load remote resources for immediate use
When to Use
Use fetchToBase64() when:
- You need to display content (images, etc.)
- You need to process data in memory
- You want to create data URLs
- File is small (<10MB)
Use downloadFromUrl() when:
- You want to save directly to disk
- File is large (more memory efficient)
- You don't need content in memory
- You're downloading multiple files
Technical Notes
- Base64 encoding increases size by ~33%
- Large files (>10MB) may cause memory issues
- For large files, use
downloadFromUrl()instead - Use
atob()to decode base64 back to binary string