Skip to content

File helpers ​

Four helpers for getting a file out of the browser and back in again.

Open in demo
Open in demo

Import ​

ts
import { downloadBlob, fileToBase64, getFileExtension, readFileAsText } from '@shared/utils/file'

downloadBlob ​

ts
function downloadBlob(data: Blob | string, filename: string, mimeType?: string): void
ts
downloadBlob(new Blob([csv], { type: 'text/csv' }), 'report.csv')
downloadBlob('hello', 'note.txt')

A string is wrapped in a Blob for you, using mimeType — which defaults to text/plain;charset=utf-8.

The object URL is revoked on the next frame, not in the same tick. Same-tick revocation cancels the download in Safari and older Firefox.

fileToBase64 ​

ts
function fileToBase64(file: Blob): Promise<string>
ts
const preview = await fileToBase64(file)

Returns a full data URL — data:image/png;base64,iVBORw0…. The prefix is kept, since that is what <img src> needs.

readFileAsText ​

ts
function readFileAsText(file: Blob, encoding?: string): Promise<string>
ts
const csv = await readFileAsText(file)
const legacy = await readFileAsText(file, 'windows-1256')

encoding defaults to 'utf-8'. Pass the real one for a legacy export: a Windows-1256 Arabic CSV read as UTF-8 comes back as mojibake rather than as an error, which is far harder to notice.

getFileExtension ​

ts
function getFileExtension(filename: string): string
ts
getFileExtension('Quarterly Report.PDF') // 'pdf'

Lower-cased, without the dot, and '' when there is none — so it is always safe to compare.

Three cases name.split('.').pop() gets wrong and this does not: a dotfile such as .gitignore, a double extension such as archive.tar.gz, and a dot in a directory name such as v1.2/report.