File size: 1,021 Bytes
1d8be9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
export const MAX_UPLOAD_BYTES = 20_000_000;
export const MAX_UPLOAD_LABEL = "20 MB";

const SUPPORTED_TYPES = new Set(["image/jpeg", "image/png", "image/webp"]);
const SUPPORTED_EXTENSIONS = /\.(jpe?g|png|webp)$/i;

export function validateImageFile(file: File): string | null {
  if (file.size === 0) {
    return "This file is empty. Choose a JPG, PNG, or WEBP image.";
  }
  if (file.size > MAX_UPLOAD_BYTES) {
    return `This image is larger than the ${MAX_UPLOAD_LABEL} upload limit.`;
  }

  const mediaType = file.type.trim().toLowerCase();
  const hasSupportedType = SUPPORTED_TYPES.has(mediaType);
  const hasSupportedExtension = SUPPORTED_EXTENSIONS.test(file.name);
  if (!hasSupportedType && (mediaType !== "" || !hasSupportedExtension)) {
    return "Choose a JPG, PNG, or WEBP image.";
  }

  return null;
}

export function formatFileSize(bytes: number): string {
  if (bytes < 1_000_000) {
    return `${Math.max(1, Math.round(bytes / 1_000))} KB`;
  }
  return `${(bytes / 1_000_000).toFixed(1)} MB`;
}