File Preview
A lazy preview of a single stored file — image, PDF or text — with metadata, resolving bytes only when it mounts.
Previews one stored file by key (or its resolved FileInfo). Images prefer a direct url(), falling back to the gateway download proxy when the adapter can’t sign; PDFs are downloaded and rendered from a blob: URL (or loaded by URL, when your gateway serves them inline); text is fetched and shown inline. Bytes load only when the component mounts.
"use client";
import { UploadIcon } from "lucide-react";
import type { ChangeEvent } from "react";
import { useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { demoFiles } from "@/lib/demo-files";
import { FilePreview } from "@/registry/files-sdk/file-preview/file-preview";
const Example = () => {
const files = demoFiles;
const inputRef = useRef<HTMLInputElement>(null);
// Start on a text file the demo store seeds, so the preview is populated;
// uploading swaps it out.
const [key, setKey] = useState<string>("documents/meeting-notes.txt");
const handleChange = async (event: ChangeEvent<HTMLInputElement>) => {
// Capture the element now — React nulls `currentTarget` after the handler's
// synchronous phase, so it's gone by the time the upload below resolves.
const input = event.currentTarget;
const file = input.files?.[0];
if (!file) {
return;
}
const result = await files.upload(`demo/${file.name}`, file, {
contentType: file.type,
});
setKey(result.key);
input.value = "";
};
return (
<div className="flex flex-col gap-4">
<div>
<Button
onClick={() => inputRef.current?.click()}
type="button"
variant="outline"
>
<UploadIcon />
Choose a file
</Button>
<input
accept="image/*,text/*,application/pdf"
aria-label="Choose a file to preview"
className="hidden"
onChange={(event) => {
void handleChange(event);
}}
ref={inputRef}
type="file"
/>
</div>
<FilePreview file={key} files={files} />
</div>
);
};
export default Example;
Installation
npx shadcn@latest add https://files-sdk.dev/r/file-preview.jsonUsage
import { useFiles } from "files-sdk/react";
import { FilePreview } from "@/components/files-sdk/file-preview";
export function Preview({ fileKey }: { fileKey: string }) {
const files = useFiles({ endpoint: "/api/files" });
return <FilePreview file={fileKey} files={files} />;
}
The footer shows the key, size, type and etag. Pass either a key string (the component head()s it for metadata) or an already-resolved FileInfo (a list() item, say) to skip that round-trip.
Sizing the preview
className styles the outer <figure>. To size the preview itself, pass previewClassName, which is merged into the built-in preview element: the PDF <object>, the <img> or the text <pre>. PDFs default to h-72 and images and text to max-h-72, and conflicting utilities replace those defaults. To fill most of a tall container like a sheet:
<FilePreview
file={fileKey}
files={files}
previewClassName="h-[80vh] max-h-none"
/>
PDFs and text get 80vh of height and images scale to fit within it. A renderPreview viewer doesn’t receive previewClassName; size it with its own classes.
Files without a real content type
Objects stored as application/octet-stream (or with no type at all) are common when something other than a browser wrote them. FilePreview previews those by their key’s extension instead: .pdf, raster images (.png, .jpg, .gif, .webp, .avif, .bmp) and text (.txt, .md, .csv, .log, .json). An extension-less key is checked for the PDF signature with a 5-byte range read, on adapters that support range reads, and previewed as a PDF when it matches. The footer still shows the stored type.
To store the right type in the first place, add the contentType() plugin on the server. It sniffs the bytes of each upload that goes through your Files instance and replaces a generic application/octet-stream with the detected type.
When another system writes the objects and you can’t change their stored type, override it per request instead: return responseContentType from the gateway’s authorize (for example "application/pdf" alongside an inline disposition), and both the signed URL and the download proxy serve that type. That changes what the browser receives, not what head() reports, so FilePreview still picks its renderer from the stored type, the extension, or the PDF signature above. The override matters with pdfSource="url", below, where the browser loads the URL itself and would download a PDF served as application/octet-stream.
Why PDFs use a blob: URL
The gateway forces Content-Disposition: attachment on both url() and the download proxy — its stored-XSS guard against user-uploaded HTML and script-bearing SVGs. Browsers honor that header even for a document loaded inside an <object> tag, so a gateway URL would trigger a download instead of an inline PDF render. FilePreview sidesteps this by fetching the bytes through download() and previewing a blob: URL, which carries no headers — no server configuration needed, and the XSS guard stays intact. If you’d rather serve PDFs inline directly (to name the file the viewer saves, say), return an inline disposition from authorize and set pdfSource="url", below.
Naming the viewer’s download
A browser’s built-in PDF viewer names the file its Download button saves after the filename in the response’s Content-Disposition. A blob: URL has no response headers, so a blob preview saves under a name the browser makes up (a random ID in Chrome, document.pdf in Firefox). Wrapping the bytes in a named File doesn’t change that.
To choose the name, have authorize serve those PDFs inline with a filename, and set pdfSource="url":
createFilesRouter({
files,
authorize: async ({ operation, key, req }) => {
const session = await auth(req);
if (
(operation === "url" || operation === "download") &&
key?.startsWith("batches/")
) {
const batch = await getBatch(session, key); // your lookup
return { disposition: `inline; filename="${batch.id}.pdf"` };
}
// ...the rest of your policy
},
});
<FilePreview file={fileKey} files={files} pdfSource="url" />
FilePreview then skips its own download and points the viewer at a signed URL, which binds that Content-Disposition, or at the gateway’s download proxy, which sends it as given. The browser fetches the PDF once, can stream it, and saves it under the batch ID. A renderPreview viewer gets the same URL, so a custom viewer costs one fetch too.
- Return the inline disposition for both
urlanddownload:FilePreviewsigns a URL when the adapter can and uses the proxy otherwise. Without it, the gateway’sattachmentdefault applies and the PDF downloads instead of previewing. - Scope it to keys whose content you control, like PDFs your server composes. Inline turns off the gateway’s
attachmentguard for those keys. - A name containing
",\or non-ASCII characters needs RFC 6266 escaping (filename*=UTF-8''…). - Some adapters can’t bind a disposition into their URLs (see provider gaps). On those,
FilePreviewloads PDFs through the proxy, but the gateway’s defaultdownloadMode: "auto"still redirects an inline download to a URL without the header. SetdownloadMode: "proxy"on the gateway to keep the filename. - Only PDFs stored as
application/pdfload by URL. A PDF stored with a generic type and recognized by its extension or signature would be served asapplication/octet-stream, which browsers download instead of rendering, so it still previews from ablob:URL (and its viewer saves it under a made-up name). Store the right type to name it.
Custom viewers
Pass renderPreview to replace the built-in preview with your own viewer component — a PDF, DOCX or CSV viewer, for example. When it’s set, a src is resolved for every non-text type (not just images and PDFs), so viewers for formats the built-in preview can’t render still get a URL:
<FilePreview
file={fileKey}
files={files}
renderPreview={({ type, src, text }) => {
if (type === "application/pdf" && src) {
return <PDFViewer className="h-[640px]" src={src} />;
}
if (type === "text/csv" && text) {
return <CsvTable data={text} />;
}
return <p className="text-muted-foreground text-sm">No preview</p>;
}}
/>
The callback receives the resolved FileInfo plus the same type, src and text the built-in preview would use. type is the stored type without parameters (text/csv, not text/csv; charset=utf-8), or the inferred one for files without a real content type, so branch on it rather than file.contentType. PDFs arrive as a blob: URL (the bytes are already downloaded, so reading it costs no second request), or as a signed or proxy URL with pdfSource="url" when they’re stored as application/pdf; other types as a signed or proxy URL.
Props
filesUseFilesResult
A `useFiles()` instance — resolves metadata and bytes through it.
UseFilesResultfilestring | FileInfo
A key string, or an already-resolved `FileInfo` (e.g. a `list()` item).
string | FileInfoendpoint?string
Endpoint for the gateway download-proxy fallback. Default `"/api/files"`.
stringpdfSource?"blob" | "url"
How a PDF reaches the preview. `"blob"` (the default) downloads the bytes and previews a `blob:` URL, which renders inline even though the gateway forces `Content-Disposition: attachment`. `"url"` skips that download and points the viewer at a signed URL, or the gateway download proxy, so the browser fetches the PDF itself — once, streamed, and saved by the viewer's Download button under the `filename` the response's `Content-Disposition` carries. Use `"url"` only when `authorize` returns an inline disposition for `url` and `download` on these keys; otherwise the PDF downloads instead of previewing. A PDF stored with a generic type (`application/octet-stream`) still previews from a `blob:` URL: its URL would serve it under that type, which browsers don't render as a PDF.
"blob" | "url"renderPreview?(preview: {
file: FileInfo;
type: string;
src?: string;
text?: string;
}) => ReactNode
Replace the built-in preview with a custom viewer (e.g. a PDF, DOCX or CSV viewer component). Called once metadata resolves, with the same `type`, `src` and `text` the built-in preview would use — except that when this is set, a `src` is resolved for **every** non-text type, not just images and PDFs, so viewers for formats the built-in preview can't render still get a URL. PDFs arrive as a `blob:` URL, or as a signed or proxy URL under `pdfSource="url"` when stored as `application/pdf`; other types as a signed or proxy URL. `type` is the stored type without parameters, or the inferred one when the stored type is generic (`application/octet-stream`).
(preview: {
file: FileInfo;
type: string;
src?: string;
text?: string;
}) => ReactNodeclassName?string
Classes for the outer `<figure>`.
stringpreviewClassName?string
Classes merged into the built-in preview element: the PDF `<object>` (`h-72` by default), the `<img>` and the text `<pre>` (both `max-h-72`). Conflicting utilities replace the defaults, so `"h-[80vh] max-h-none"` makes PDFs and text 80vh tall and fits images within that height. Not applied to a `renderPreview` viewer.
string