-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasset.ts
54 lines (48 loc) · 1.44 KB
/
asset.ts
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
import { Exception, FS, UploadFile, UploadFileResponse } from "@yao/runtime";
/**
* The public directory for the uploaded files
*/
export const PublicUploadRoot = "/public/assets/upload";
/**
* Upload an image file to the public directory
*/
function UploadImageToPublic(file: UploadFile): UploadFileResponse {
const root = `${PublicUploadRoot}/images`;
const fs = new FS("app");
const tmpfile = file.tempFile;
const ext = fs.ExtName(file.name);
// Check the file name jpg, jpeg, png, svg, gif, webp
if (!/^(jpg|jpeg|png|svg|gif|webp)$/i.test(ext)) {
throw new Exception(
"File format not supported, please select an image file",
400
);
}
const filename = `${Tempdir()}/${Name()}.${ext}`;
const target = `${root}/${filename}`;
fs.Move(tmpfile, target);
return `/images/${filename}`;
}
/**
* Generate a random directory name
* @returns
*/
export function Name(): string {
const random = Math.floor(Math.random() * 100000) + 1;
return `${new Date().getTime()}${random}`;
}
/**
* Generate a temporary directory name
* @returns
*/
export function Tempdir(): string {
const today: Date = new Date();
const year: number = today.getFullYear();
const month: number = today.getMonth() + 1;
const day: number = today.getDate();
// Format the date to YYYYMMDD
const formattedDate: string = `${year}${month
.toString()
.padStart(2, "0")}${day.toString().padStart(2, "0")}`;
return formattedDate;
}