File helpers
formatFileSize, fileKind, saveFile, openFile, viewableType and useObjectUrl — a byte count as people read it, what kind of file a MIME type or a name is, saving a file, opening one in a new tab behind a safe-type allowlist, and showing an uploaded Blob in the page without letting it run as your app.
Plain functions behind FileItem, FileUpload, DownloadButton and FilePreview, exported from the package root for your own table cells, captions, messages and menu items. They take no React, so they work in a loader or a test as well. One hook joins them, useObjectUrl: the URL for a Blob in your own <img>.
import { fileKind, formatFileSize, openFile, saveFile, useObjectUrl, viewableType } from '@42-central/ui-react';formatFileSize
A byte count in decimal units (1 MB is 1,000,000 bytes, as operating systems show it), to three significant digits, with the locale's own unit names and separators.
formatFileSize(48_213); // "48.2 kB"
formatFileSize(48_213, 'fr-FR'); // "48,2 ko"
formatFileSize(1_234_567, 'fr-FR'); // "1,23 Mo"
formatFileSize(5 * 1024 * 1024); // "5.24 MB"The locale defaults to DEFAULT_LOCALE ("en-US"), never the runtime's, so a server render and the browser can't disagree. In a component, pass useLocale() to follow the IntlProvider:
const locale = useLocale();
<td>{formatFileSize(document.size, locale)}</td>That is the kit's one pattern for Intl formatting: the hook resolves the locale, and the formatting stays a plain function you can call anywhere. There is no useFormatFileSize.
Prop
Type
Returns a string.
fileKind
The kind of a file, from its MIME type, or from its name's extension when the type is empty or generic: browsers often report "" for a .csv or a .docx, and servers send application/octet-stream. One of FILE_KINDS: image, video, audio, pdf, text, archive, spreadsheet, document, code, font or other.
fileKind('application/pdf'); // "pdf"
fileKind('text/csv'); // "spreadsheet", not "text": an exact type wins over its family
fileKind('', 'grades.csv'); // "spreadsheet"
fileKind('application/octet-stream', 'backup.tar.gz'); // "archive"
fileKind(file.type, file.name); // a picked FileOne lookup decides, trying an exact MIME type, then its family (image/*), then the extension. FileItem keys its icons by these kinds.
Prop
Type
Returns a FileKind. extensionOf(name) is the extension it reads: ".pdf" for "Report.FINAL.PDF", "" without one.
saveFile
Saves a Blob, a File or a URL as a file, through a hidden link with a download attribute. It's what DownloadButton calls; reach for it directly when the download doesn't start from a button (a menu item, a shortcut, the end of a form submission). It makes no request: fetch the file first, and pass the Blob.
saveFile(new Blob([csv], { type: 'text/csv' }), 'grades.csv');
saveFile(file); // a File keeps its own name
saveFile('/exports/grades.csv', 'Q1.csv'); // a same-origin URL, renamed
saveFile(presignedUrl); // a cross-origin URL: named by the server- A Blob or a File is saved through an object URL. The name defaults to the File's own, then to
"download".typeretypes a Blob without one (new Blob([csv])has none), without copying it. - A same-origin URL, or a
blob:ordata:one, is downloaded undername, which defaults to its last path segment. - A cross-origin URL is followed like a link. Browsers ignore the file name on it, so the server's
Content-Dispositionnames the file, and withoutattachmentthe browser shows the file rather than saving it. See Filenames from presigned URLs. - On the server it does nothing, so shared code can call it during a render or in a loader.
Revoking an object URL right after the click has cancelled the download in Safari (WebKit bug 185531, and again on iOS in 212279): the browser reads the URL after click() returns, not during it. A zero-millisecond timer only moves the race one task later. saveFile revokes it SAVE_FILE_REVOKE_DELAY (40 s) later, the delay FileSaver.js uses for the same reason. The Blob stays in memory that long, which the download needs anyway.
Prop
Type
Returns nothing.
openFile
Opens a Blob, a URL, or what your function resolves in a new tab: the "Open in new tab" behind FilePreview.Open. Call it in a click handler.
openFile(file); // a picked File
openFile(presignedUrl, { name: 'consent.pdf' });
openFile(({ signal }) => api.blob(`/documents/${id}`, { signal }), { name: 'contract.pdf' });- Popup-safe. The tab opens synchronously in the click, before your function is called, then shows the file when the promise resolves. It closes again if the promise rejects or
signalaborts, and the returned promise rejects. - A blocked popup saves the file with
saveFile, and resolves"saved"instead of"opened". - Only allowlisted files are shown (
viewableType, below). Anything else is saved, never navigated to: an uploaded HTML or SVG would run as your app. A cross-origin URL is always followed (its script runs with its own origin); a same-origin one only when its type or name is viewable; ablob:ordata:string never. - The tab can't reach back: its
openeris cut before anything loads. - The object URL lives while the tab shows it, checked every
OPEN_FILE_POLL(2 s), and is revoked once the tab closes or navigates away, or afterOPEN_FILE_MAX_AGE(one hour). Saving from the browser's PDF viewer and reloading keep working meanwhile.
The tab's title is the PDF's own Title metadata, or the object URL's id without it: set the title where the PDF is generated. See The tab's title.
Prop
Type
Returns a Promise<"opened" | "saved">.
viewableType
The type a browser may render a file under, or undefined when it must only be saved. The one allowlist FilePreview, openFile and useObjectUrl share: always one of a fixed set, never the file's own type passed through, so re-wrap the Blob under it before making an object URL (useObjectUrl does it for you).
viewableType('application/pdf', 'contract.pdf'); // "application/pdf"
viewableType('', 'scan.JPG'); // "image/jpeg"
viewableType('text/csv', 'grades.csv'); // "text/plain;charset=utf-8"
viewableType('text/html', 'contract.pdf'); // undefined: the type says HTML
viewableType('image/svg+xml', 'logo.svg'); // undefined: SVG runs script
const safe = viewableType(file.type, file.name);
if (safe) url = URL.createObjectURL(file.slice(0, file.size, safe));The set: application/pdf; image/png, jpeg, gif, webp, avif, bmp; video/mp4, webm, ogg, quicktime; audio/mpeg, mp4, aac, wav, ogg, webm, flac; and plain text (text, Markdown, CSV, TSV, JSON) as text/plain;charset=utf-8. The kind is fileKind's, so a specific type wins over the name. Why these and nothing else is measured in FilePreview's Security section.
Prop
Type
Returns a string or undefined.
useObjectUrl
A URL for a Blob or a File that's safe to put in your page: in an <img>, a <video>, a link. The one mechanism behind every kit surface that shows a Blob: FileItem and FileUpload thumbnails, FilePreview, ImageCropper and PhotoCapture.
const url = useObjectUrl(file);
<img src={url} alt="" />Never URL.createObjectURL(file) for an uploaded file. An object URL has your app's origin: the <img> won't run an SVG's script, but "Open image in new tab", dragging the image to the tab bar or copying its address navigates to the URL, and an .svg or .html there runs as your app, with its storage and its API. What useObjectUrl hands out instead:
| The Blob | The URL |
|---|---|
On viewableType's list: PDF, PNG, JPEG, GIF, WebP, AVIF, BMP, common video and audio, plain text | An object URL for the Blob re-wrapped under that type, never the type it claims. Revoked when the Blob changes or the component unmounts. |
| SVG, by type, or by name for a missing or generic type | A data: URL. Its document has an opaque origin, so its script can't reach your app even in a tab of its own. Up to SVG_DATA_URL_LIMIT (5 MB); past it, none. |
| Anything else: HTML, XML, an unknown or "binary" type | undefined. Show an icon, or offer a download with saveFile. |
| A string | Passed through: your URL, under your server's Content-Type. |
Why 5 MB for an SVG. A data: URL lives as a string, a third larger than the file in base64, plus the <img>'s copy, for every mounted thumbnail. An SVG past 5 MB is a map or an export, not a logo, and a list of them would hold that many times over. FileItem shows its kind icon then, and FilePreview its download panel.
A Blob with no type, such as new Blob([bytes]), is shown only by its name: a File's own, or options.name. Pass options.type when you know better than the Blob.
It keeps the guarantees of a hand-rolled one: the URL is made in an effect, so it's undefined on the server and for the first render (an SVG's until it's read), Strict Mode's double render leaks nothing, and a render after the Blob changes never hands out the previous, already revoked URL.
Prop
Type
Returns a string, or undefined while the URL is made, and for a Blob it won't show. A live demo is on the useObjectUrl hook page.