forked from mxx1111/mdlook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload-filename.ts
More file actions
54 lines (44 loc) · 1.41 KB
/
Copy pathupload-filename.ts
File metadata and controls
54 lines (44 loc) · 1.41 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const MIME_TO_EXT: Record<string, string> = {
'image/jpeg': `jpg`,
'image/jpg': `jpg`,
'image/png': `png`,
'image/gif': `gif`,
'image/webp': `webp`,
'image/svg+xml': `svg`,
'image/bmp': `bmp`,
'image/avif': `avif`,
'image/x-icon': `ico`,
'image/vnd.microsoft.icon': `ico`,
}
const INVALID_EXTENSIONS = new Set([`blob`, `bin`, `octet-stream`])
function extensionFromMime(mimeType: string): string | null {
const mime = mimeType.trim().toLowerCase()
if (!mime)
return null
const mapped = MIME_TO_EXT[mime]
if (mapped)
return mapped
const [, subtype] = mime.split(`/`)
if (!subtype || subtype === `octet-stream`)
return null
return subtype.split(`+`)[0] || null
}
function extensionFromFilename(filename: string): string | null {
const name = filename.trim()
const dotIndex = name.lastIndexOf(`.`)
if (dotIndex <= 0 || dotIndex >= name.length - 1)
return null
const ext = name.slice(dotIndex + 1).toLowerCase()
if (!ext || INVALID_EXTENSIONS.has(ext) || ext.length > 10)
return null
return ext
}
export function resolveImageExtension(filename: string, mimeType: string): string {
return extensionFromFilename(filename)
?? extensionFromMime(mimeType)
?? `png`
}
export function buildDatedObjectKey(filename: string, mimeType: string): string {
const ext = resolveImageExtension(filename, mimeType)
return `${Date.now()}-${crypto.randomUUID()}.${ext}`
}