File Download Reference
Use useDownload to save generated data, uploaded files, AI outputs, and client-side media processing results to the user's device.
useDownload
Import the hook from the download module:
import { useDownload } from "@/hooks/use-download";
type Panel = { id: string; imageUrl: string; name: string };
export default function App({ panels }: { panels: Panel[] }) {
const { download } = useDownload();
const [isZipping, setIsZipping] = React.useState(false);
const handleDownloadAll = async () => {
setIsZipping(true);
try {
const zip = new JSZip();
for (let index = 0; index < panels.length; index++) {
const panel = panels[index];
const response = await fetch(panel.imageUrl);
const blob = await response.blob();
const filename = `${String(index + 1).padStart(2, "0")}-${panel.name}.png`;
zip.file(filename, blob);
}
const zipBlob = await zip.generateAsync({ type: "blob" });
download(zipBlob, "my-export.zip");
} finally {
setIsZipping(false);
}
};
return (
<button onClick={handleDownloadAll} disabled={isZipping || panels.length === 0}>
{isZipping ? <span className="inline-block w-4 h-4 animate-spin rounded-full border-2 border-current border-t-transparent" /> : null}
Download all
</button>
);
}
Useful JSZip operations:
const zip = new JSZip();
zip.file("readme.txt", "Hello World");
zip.file("data.json", JSON.stringify(data, null, 2));
zip.folder("images")?.file("photo.png", imageBlob);
const blob = await zip.generateAsync({ type: "blob" });
Error Handling
const { download, error, clearError } = useDownload({
onError: (err) => {
console.error("Download failed:", err.message);
},
});
if (error) {
console.error("Download error:", error.message);
clearError();
}
Best Practices
- Let the hook infer media types from filenames when possible.
- Omit the filename for
Fileresults that already include the correct extension. - Use
{ url }for hosted files and generated media URLs. - Show a loading state when building ZIP files or fetching many remote files.
- Use zero-padded filenames in ZIP exports so files sort correctly.
- Organize ZIP contents with folders and include a manifest when exports need context.
- Handle remote fetch failures when batching files from URLs.