@ubuligan/file-preview-utils
v1.0.0
Published
Lightweight TypeScript utilities to preview and convert files (Blob ↔ Base64) with no dependencies.
Maintainers
Readme
@ubuligan/file-preview-utils
A lightweight TypeScript utility package for converting files from Blob to Base64 and previewing images, PDFs, and other files in a new browser window. Works with any axios-like HTTP client for maximum flexibility.
Features
- 🚀 Zero dependencies - Uses native browser APIs
- 📁 File conversion - Convert Blob objects to Base64 strings
- 🖼️ Image preview - Display images in new browser windows
- 📄 PDF handling - Open PDFs in browser for viewing
- 💾 File downloads - Automatic download for other file types
- 🔧 TypeScript support - Full type definitions included
- 🌐 HTTP client agnostic - Works with axios, fetch wrappers, or any compatible client
Installation
npm install @ubuligan/file-preview-utilsQuick Start
import axios from "axios";
import { previewFile, blobToBase64 } from "@ubuligan/file-preview-utils";
// Preview a file (images open in new window, PDFs open in browser, others download)
await previewFile("/api/files/document.pdf", "document.pdf", axios);
// Convert a blob to base64
const blob = new Blob(["Hello World"], { type: "text/plain" });
const base64String = await blobToBase64(blob);API Reference
previewFile(url, fileName, httpClient, isEdocMainFile?)
Opens or downloads a file from a given URL depending on its type.
Parameters:
url(string) - File URL to preview or downloadfileName(string) - Desired file name for downloadshttpClient(HttpClient) - An axios-like HTTP client instanceisEdocMainFile?(boolean) - Optional flag to add{ edocDocument: true }param
Behavior:
- Images (
image/*): Opens in a new browser window - PDFs (
application/pdf): Opens in browser for viewing - Other files: Triggers download with specified filename
Example:
import axios from "axios";
import { previewFile } from "@ubuligan/file-preview-utils";
// Preview an image
await previewFile("/api/images/photo.jpg", "photo.jpg", axios);
// Preview a PDF
await previewFile("/api/documents/report.pdf", "report.pdf", axios);
// Download a document
await previewFile("/api/files/data.xlsx", "data.xlsx", axios);
// With edoc flag
await previewFile("/api/edoc/document.pdf", "document.pdf", axios, true);blobToBase64(blob)
Converts a Blob object to a Base64 string.
Parameters:
blob(Blob) - The Blob to convert
Returns:
Promise<string>- Base64 encoded string (includes data URL prefix)
Example:
import { blobToBase64 } from "@ubuligan/file-preview-utils";
// Convert file input to base64
const fileInput = document.getElementById("file") as HTMLInputElement;
const file = fileInput.files?.[0];
if (file) {
const base64 = await blobToBase64(file);
console.log(base64); // "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
}
// Convert response data to base64
const response = await axios.get("/api/image", { responseType: "blob" });
const base64 = await blobToBase64(response.data);HTTP Client Interface
The package works with any HTTP client that implements the HttpClient interface:
interface HttpClient {
get<T>(
url: string,
config?: {
responseType?: string;
params?: Record<string, any>;
}
): Promise<{
status: number;
data: T;
headers: Record<string, string>;
}>;
}Using with Different HTTP Clients
Axios (Recommended)
import axios from "axios";
import { previewFile } from "@ubuligan/file-preview-utils";
await previewFile("/api/file.pdf", "file.pdf", axios);Custom Fetch Wrapper
import { previewFile } from "@ubuligan/file-preview-utils";
const fetchClient = {
async get(url: string, config?: any) {
const response = await fetch(url);
return {
status: response.status,
data: await response.blob(),
headers: Object.fromEntries(response.headers.entries()),
};
},
};
await previewFile("/api/file.pdf", "file.pdf", fetchClient);Error Handling
import { previewFile } from "@ubuligan/file-preview-utils";
try {
await previewFile("/api/file.pdf", "file.pdf", axios);
} catch (error) {
console.error("Failed to preview file:", error);
}The previewFile function logs errors to the console when the HTTP response status is not 200.
Browser Compatibility
- Modern browsers with FileReader API support
- ES2017+ for async/await syntax
- Blob and URL APIs for file handling
Use Cases
Document Management Systems
// Preview user-uploaded documents
const handleFilePreview = async (fileId: string, fileName: string) => {
await previewFile(`/api/documents/${fileId}`, fileName, axios);
};Image Galleries
// Display images in new windows
const showImage = async (imageUrl: string, imageName: string) => {
await previewFile(imageUrl, imageName, axios);
};File Conversion Utilities
// Convert uploaded files to base64 for storage
const convertFileToBase64 = async (file: File): Promise<string> => {
return await blobToBase64(file);
};TypeScript Support
This package is written in TypeScript and includes full type definitions. No additional @types packages are needed.
import {
previewFile,
blobToBase64,
HttpClient,
} from "@ubuligan/file-preview-utils";
// All functions are fully typed
const client: HttpClient = axios;
const result: Promise<void> = previewFile("/api/file", "file.pdf", client);
const base64: Promise<string> = blobToBase64(new Blob());Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT © Javid Salimov
