The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
import { cn, resizeImage } from "@dub/utils";
import { VariantProps, cva } from "class-variance-authority";
import { DragEvent, ReactNode, useEffect, useState } from "react";
import { toast } from "sonner";
import { CloudUpload, Icon, LoadingCircle } from "./icons";
type AcceptedFileFormats = "any" | "images" | "csv" | "documents";
const documentTypes = [
"application/pdf", // .pdf
"text/plain", // .txt
"application/msword", // .doc
"application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .docx
"application/vnd.ms-excel", // .xls
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xlsx
"text/csv", // .csv
];
const imageExtensionMimeTypes: Record<string, string> = {
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
webp: "image/webp",
avif: "image/avif",
svg: "image/svg+xml",
};
const acceptFileTypes: Record<
AcceptedFileFormats,
{ types: string[]; errorMessage?: string }
> = {
any: { types: [] },
images: {
types: ["image/png", "image/jpeg", "image/webp", "image/avif"],
errorMessage: "File type not supported (.png, .jpg, .webp, or .avif only)",
},
csv: {
types: ["text/csv"],
errorMessage: "File type not supported (.csv only)",
},
documents: {
types: documentTypes,
errorMessage: "File type not supported (document files only)",
},
};
const imageUploadVariants = cva(
"group relative isolate flex aspect-[1200/630] w-full flex-col items-center justify-center overflow-hidden bg-white transition-all hover:bg-neutral-50",
{
variants: {
variant: {
default: "rounded-md border border-neutral-300 shadow-sm",
plain: "",
},
},
defaultVariants: {
variant: "default",
},
},
);
type FileUploadReadFileProps =
| {
/**
* Whether to automatically read the file and return the result as `src` to onChange
*/
readFile?: false;
onChange?: (data: { file: File }) => void;
}
| {
/**
* Whether to automatically read the file and return the result as `src` to onChange
*/
readFile: true;
onChange?: (data: { file: File; src: string }) => void;
};
export type FileUploadProps = FileUploadReadFileProps & {
id?: string;
accept?: AcceptedFileFormats;
/**
* When set, overrides the MIME types from the `accept` preset.
*/
acceptedFileTypes?: readonly string[];
className?: string;
iconClassName?: string;
previewClassName?: string;
icon?: Icon;
/**
* Custom preview component to display instead of the default
*/
customPreview?: ReactNode;
/**
* Image to display (generally for image uploads)
*/
imageSrc?: string | null;
/**
* Whether to display a loading spinner
*/
loading?: boolean;
/**
* Whether to allow clicking on the area to upload
*/
clickToUpload?: boolean;
/**
* Whether to show instruction overlay when hovered
*/
showHoverOverlay?: boolean;
/**
* Content to display below the upload icon (null to only display the icon)
*/
content?: ReactNode | null;
/**
* Desired resolution to suggest and optionally resize to
*/
targetResolution?: { width: number; height: number };
/**
* A maximum file size (in megabytes) to check upon file selection. Default is 5MB.
*/
maxFileSizeMB?: number;
/**
* Accessibility label for screen readers
*/
accessibilityLabel?: string;
disabled?: boolean;
"data-testid"?: string;
} & VariantProps<typeof imageUploadVariants>;
export function FileUpload({
id,
readFile,
onChange,
variant,
className,
iconClassName,
previewClassName,
icon: Icon = CloudUpload,
customPreview,
accept = "any",
acceptedFileTypes,
imageSrc,
loading = false,
clickToUpload = true,
showHoverOverlay = true,
content,
maxFileSizeMB = 5,
targetResolution,
accessibilityLabel = "File upload",
disabled = false,
"data-testid": dataTestId,
}: FileUploadProps) {
const [dragActive, setDragActive] = useState(false);
const [fileName, setFileName] = useState<string | null>(null);
const [imageError, setImageError] = useState(false);
useEffect(() => {
setImageError(false);
}, [imageSrc]);
const resolvedAcceptedTypes =
acceptedFileTypes ?? acceptFileTypes[accept].types;
const onFileChange = async (
e: React.ChangeEvent<HTMLInputElement> | DragEvent,
) => {
const file =
"dataTransfer" in e
? e.dataTransfer.files && e.dataTransfer.files[0]
: e.target.files && e.target.files[0];
if (!file) return;
setFileName(file.name);
if (maxFileSizeMB > 0 && file.size / 1024 / 1024 > maxFileSizeMB) {
toast.error(`File size too big (max ${maxFileSizeMB} MB)`);
return;
}
const extension = file.name.split(".").pop()?.toLowerCase();
const mimeType =
file.type || (extension ? imageExtensionMimeTypes[extension] : "") || "";
if (
resolvedAcceptedTypes.length &&
!resolvedAcceptedTypes.includes(mimeType)
) {
toast.error(
acceptedFileTypes
? "File type not supported"
: acceptFileTypes[accept].errorMessage ?? "File type not supported",
);
return;
}
let fileToUse =
!file.type && mimeType
? new File([file], file.name, { type: mimeType })
: file;
// Add image resizing logic
if (targetResolution && mimeType.startsWith("image/")) {
try {
const resizedFile = await resizeImage(fileToUse, targetResolution);
const blob = await fetch(resizedFile).then((r) => r.blob());
fileToUse = new File([blob], fileToUse.name, {
type: blob.type || "image/jpeg",
});
} catch (error) {
console.error("Error resizing image:", error);
// Fallback to original file if resize fails
}
}
// File reading logic
if (readFile) {
const reader = new FileReader();
reader.onload = (e) =>
onChange?.({ src: e.target?.result as string, file: fileToUse });
reader.readAsDataURL(fileToUse);
return;
}
onChange?.({ file: fileToUse });
};
return (
<label
className={cn(
imageUploadVariants({ variant }),
!disabled
? cn(clickToUpload && "cursor-pointer")
: "cursor-not-allowed",
className,
)}
>
{loading && (
<div className="absolute inset-0 z-[5] flex items-center justify-center rounded-[inherit] bg-white">
<LoadingCircle />
</div>
)}
<div
className="absolute inset-0 z-[5]"
onDragOver={(e) => {
e.preventDefault();
e.stopPropagation();
setDragActive(true);
}}
onDragEnter={(e) => {
e.preventDefault();
e.stopPropagation();
setDragActive(true);
}}
onDragLeave={(e) => {
e.preventDefault();
e.stopPropagation();
setDragActive(false);
}}
onDrop={async (e) => {
e.preventDefault();
e.stopPropagation();
onFileChange(e);
setDragActive(false);
}}
/>
<div
className={cn(
"absolute inset-0 z-[3] flex flex-col items-center justify-center rounded-[inherit] border-2 border-transparent bg-white transition-all",
disabled && "bg-neutral-50",
dragActive &&
!disabled &&
"cursor-copy border-black bg-neutral-50 opacity-100",
imageSrc && !imageError
? cn(
"opacity-0",
showHoverOverlay && !disabled && "group-hover:opacity-100",
)
: cn(!disabled && "group-hover:bg-neutral-50"),
)}
>
<Icon
className={cn(
"size-7 transition-all duration-75",
!disabled
? cn(
"text-neutral-500 group-hover:scale-110 group-active:scale-95",
dragActive ? "scale-110" : "scale-100",
)
: "text-neutral-400",
iconClassName,
)}
/>
{content !== null && (
<div
className={cn(
"mt-2 text-center text-sm text-neutral-500",
disabled && "text-neutral-400",
)}
>
{content ?? (
<>
<p>Drag and drop {clickToUpload && "or click"} to upload.</p>
</>
)}
</div>
)}
<span className="sr-only">{accessibilityLabel}</span>
</div>
{imageSrc &&
!imageError &&
(customPreview ?? (
<img
src={imageSrc}
alt="Preview"
referrerPolicy="no-referrer"
onError={() => setImageError(true)}
className={cn(
"h-full w-full rounded-[inherit] object-cover",
previewClassName,
)}
/>
))}
{clickToUpload && (
<div className="sr-only mt-1 flex shadow-sm">
<input
id={id}
key={fileName} // Gets us a fresh input every time a file is uploaded
type="file"
accept={resolvedAcceptedTypes.join(",")}
onChange={onFileChange}
disabled={disabled}
data-testid={dataTestId}
/>
</div>
)}
</label>
);
}