file-util.ts
Overview
file-util.ts is a utility module designed to facilitate common file operations in a web application context, especially around image and document handling. It provides functions for:
Converting files to base64 strings and vice versa.
Normalizing file input from UI components.
Managing file lists for upload interfaces.
Downloading and previewing files and documents.
Formatting file sizes for display.
The module integrates tightly with frontend file input components (notably from the Ant Design library) and backend services (via fileManagerService) to fetch document blobs. It is aimed at simplifying file manipulation for upload, preview, download, and display purposes within the application.
Detailed Description of Functions
1. transformFile2Base64(val: any): Promise<any>
Converts a given File or Blob object (typically an image) into a compressed base64-encoded string.
Parameters:
val: The input file/blob to be converted.
Returns:
Promise<string>resolving with the compressed base64 string of the image.
Behavior:
Reads the file as a Data URL.
Creates an
Imageobject from the Data URL.Compresses the image by resizing it so that the maximum dimension is 100 pixels (preserving aspect ratio).
Draws the resized image onto a canvas.
Extracts the base64 string from the canvas as a PNG.
Usage Example:
const base64Str = await transformFile2Base64(selectedFile); console.log(base64Str); // Outputs compressed base64 stringImportant:
Compression is limited to max size 100px for width or height.
Output format is always PNG to maintain transparency.
2. transformBase64ToFile(dataUrl: string, filename: string = 'file'): File
Converts a base64-encoded Data URL back into a File object.
Parameters:
dataUrl: Base64 string representing the file.filename: Optional filename for the resultingFileobject (default'file').
Returns:
Fileinstance created from the base64 data.
Usage Example:
const file = transformBase64ToFile(base64String, 'image.png');Implementation Details:
Parses the MIME type from the Data URL.
Decodes base64 to binary data.
Creates a typed array for binary content.
Constructs a
Filewith proper MIME type.
3. normFile(e: any): any[]
Normalizes the file input event from upload components.
Parameters:
e: Event or file list from an upload component.
Returns:
An array of files:
If
eis already an array, returns it unchanged.Otherwise returns
e.fileListif present.
Usage:
Used to normalize upload event data for form processing.
4. getUploadFileListFromBase64(avatar: string): UploadFile[]
Generates an Ant Design UploadFile list from a single base64 string.
Parameters:
avatar: Base64-encoded image string.
Returns:
Array of
UploadFileobjects with one entry containing the base64 asthumbUrl.
Usage Example:
const fileList = getUploadFileListFromBase64(base64Avatar);Purpose:
To populate upload UI components with previewable files from base64 data.
5. getBase64FromUploadFileList(fileList?: UploadFile[]): Promise<string>
Extracts the base64 string from an Ant Design UploadFile list.
Parameters:
fileList: Optional array ofUploadFile.
Returns:
Promise resolving to a base64 string of the first file or its
thumbUrl.
Behavior:
If the file has an
originFileObj(actual file object), converts it to base64.Otherwise returns the existing
thumbUrl.
Usage Example:
const base64 = await getBase64FromUploadFileList(uploadFileList);
6. fetchDocumentBlob(id: string, mimeType?: FileMimeType): Promise<Blob>
Fetches a document's binary data blob from the backend service.
Parameters:
id: Document identifier.mimeType: Optional MIME type to override the default.
Returns:
Promise resolving to a
Blobof the document.
Implementation:
Calls
fileManagerService.getDocumentFilewith the document ID.Wraps response data in a
Blobwith the specified or returned MIME type.
Usage:
Internal helper for document preview and download functions.
7. previewHtmlFile(id: string): Promise<void>
Previews an HTML file by opening it in a new browser tab/window.
Parameters:
id: Document ID of the HTML file.
Returns:
Promise resolving when preview is triggered.
Process:
Fetches the document blob with MIME type
text/html.Creates an object URL for the blob.
Opens the link programmatically in the browser.
Revokes the URL after use.
Usage:
For previewing HTML documents fetched from backend.
8. downloadFileFromBlob(blob: Blob, name?: string): void
Triggers a browser download for a given blob with optional filename.
Parameters:
blob: Data blob to download.name: Optional filename for the downloaded file.
Returns:
voidUsage Example:
downloadFileFromBlob(blobData, 'report.pdf');Implementation:
Uses URL object and anchor tag click simulation.
9. downloadDocument({ id, filename }: { id: string; filename?: string }): Promise<void>
Downloads a document file by its ID.
Parameters:
id: Document identifier.filename: Optional filename for saving.
Returns:
Promise resolving after download is triggered.
Process:
Fetches the document blob from backend.
Calls
downloadFileFromBlobwith the blob and filename.
Usage:
Simplifies downloading files stored remotely via their ID.
10. formatBytes(x: string | number): string
Formats a file size in bytes into a human-readable string with units.
Parameters:
x: File size in bytes (number or numeric string).
Returns:
Formatted size string like "2.5 MB".
Details:
Uses binary prefixes (KB = 1024 bytes).
Rounds to one decimal if size < 10 and unit is above bytes.
Usage:
const readableSize = formatBytes(1234567); // "1.2 MB"
11. downloadJsonFile(data: Record<string, any>, fileName: string): Promise<void>
Downloads a JSON file from a JavaScript object.
Parameters:
data: Object to serialize and download.fileName: Name of the file to save as.
Returns:
Promise resolving when download is triggered.
Process:
Serializes JSON.
Creates a Blob with MIME
application/json.Triggers download using
downloadFileFromBlob.
Usage:
await downloadJsonFile({ name: 'Test' }, 'test.json');
12. transformBase64ToFileWithPreview(dataUrl: string, filename: string = 'file'): File
Converts a base64 string to a File object and attaches a preview property.
Parameters:
dataUrl: Base64 string.filename: Optional file name.
Returns:
Fileobject with an additional.previewproperty set to the base64 string.
Usage:
const fileWithPreview = transformBase64ToFileWithPreview(base64Str, 'img.png'); console.log(fileWithPreview.preview); // base64 string
13. getBase64FromFileList(fileList?: File[]): Promise<string>
Gets a base64 string from the first file in a list of raw File objects.
Parameters:
fileList: Optional array ofFileobjects.
Returns:
Promise resolving to base64 string or empty string.
Usage:
const base64 = await getBase64FromFileList(myFiles);
Important Implementation Details
Image Compression:
Image resizing uses an HTML5 canvas to scale images down to a max dimension of 100px, preserving aspect ratio and transparency by converting to PNG format.Base64 Handling:
The module carefully parses base64 data URLs to extract MIME types and binary data for conversions between files and strings.Blob Usage:
For downloading and previewing files, blobs are created and object URLs generated dynamically for efficient browser handling.Integration with Ant Design Upload:
Functions likenormFile,getUploadFileListFromBase64, andgetBase64FromUploadFileListare tailored to work smoothly with Ant Design'sUploadcomponent file lists and objects.Backend Service Integration:
fetchDocumentBlobusesfileManagerServiceto retrieve file data, abstracting away API call details from consumers.
Interaction with Other System Parts
fileManagerService:
This service is used to fetch document files by ID, likely interacting with backend APIs for file storage.Constants:
UsesFileMimeTypeconstants from a common constants module to standardize MIME types across the app.Ant Design UI Components:
Works closely with Ant Design'sUploadcomponent file structures (UploadFile), providing conversion and normalization utilities.Browser APIs:
Utilizes browser native APIs such asFileReader,Canvas,Blob, andURL.createObjectURLfor file processing and user interactions like download and preview.
Visual Diagram
Below is a flowchart representing the main functions and their relationships within file-util.ts:
flowchart TD
A[transformFile2Base64] --> B[Image Compression & Canvas]
B --> C[Return base64 string]
D[transformBase64ToFile] --> E[Parse base64 & create File]
F[normFile] --> G[Normalize Upload Event]
H[getUploadFileListFromBase64] --> I[Create UploadFile array with thumbUrl]
J[getBase64FromUploadFileList] -->|If originFileObj| A
J -->|Else| K[Return thumbUrl]
L[fetchDocumentBlob] --> M[Call fileManagerService.getDocumentFile]
M --> N[Return Blob]
O[previewHtmlFile] --> L
O --> P[Create ObjectURL & Open Link]
Q[downloadFileFromBlob] --> R[Create ObjectURL & Trigger Download]
S[downloadDocument] --> L
S --> Q
T[formatBytes] --> U[Convert bytes to human-readable string]
V[downloadJsonFile] --> W[Create Blob from JSON]
W --> Q
X[transformBase64ToFileWithPreview] --> D
X --> Y[Attach preview property]
Z[getBase64FromFileList] --> A
Summary
The file-util.ts module is a comprehensive utility library for file operations focused on web applications that handle images and documents. It provides robust facilities for:
Encoding/decoding between files and base64 strings.
Image compression for optimized previews.
File list normalization for UI components.
Downloading and previewing documents fetched from backend services.
Formatting file sizes for display.
Its design leverages both browser APIs and backend services integration, making it a critical part of the file handling infrastructure in the application.