file.uts
2.53 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import services from "@/services";
import { checkFileExists, readDirectory } from "@/utils/plus-io.uts";
import { WsCommand } from "../../constants.uts";
import { asObject, asString, getUploadStrategy, isEmptyObject, sendError, sendOk, WsCommandRouter } from "../CommandCore.uts";
async function resolveEntryType(path: string): Promise<UTSJSONObject> {
const result = {
fullPath: path,
isDirectory: false,
isFile: false,
name: ""
} as UTSJSONObject;
const lastSlash = path.lastIndexOf("/");
result.name = lastSlash != -1 ? path.slice(lastSlash + 1) : path;
let isDirectory = false;
try {
await readDirectory(path);
isDirectory = true;
} catch {}
if (isDirectory) {
result.isDirectory = true;
return result;
}
const fileExists = await checkFileExists(path);
if (fileExists) {
result.isFile = true;
}
return result;
}
export function registerFileHandlers(router: WsCommandRouter, defaultRootPath: string): void {
router.register(WsCommand.FileExplorer as string, async (ctx, payload): Promise<void> => {
const targetPath = asString(payload.path, defaultRootPath);
const exists = await checkFileExists(targetPath);
if (!exists) {
await sendError(ctx, `路径不存在: ${targetPath}`, payload);
return;
}
const names = await readDirectory(targetPath).catch((): string[] => []);
const files: UTSJSONObject[] = [];
for (const name of names) {
const fullPath = targetPath.endsWith("/") ? `${targetPath}${name}` : `${targetPath}/${name}`;
const info = await resolveEntryType(fullPath);
files.push(info);
}
await sendOk(ctx, "获取目录成功", {
currentPath: targetPath,
files
} as UTSJSONObject, payload);
});
router.register(WsCommand.UploadFile as string, async (ctx, payload): Promise<void> => {
const filePath = asString(payload.filePath);
if (filePath == "") {
await sendError(ctx, "文件路径不能为空", payload);
return;
}
const options = {
filePath
} as UTSJSONObject;
const uploadUrl = asString(payload.uploadUrl);
if (uploadUrl != "") {
options.uploadUrl = uploadUrl;
}
const formData = asObject(payload.formData);
if (!isEmptyObject(formData)) {
options.formData = formData;
}
const header = asObject(payload.header);
if (!isEmptyObject(header)) {
options.header = header;
}
const strategy = getUploadStrategy(asString(payload.strategy));
const result = strategy == null
? await services.fileUpload.upload(options)
: await services.fileUpload.upload(options, strategy);
await sendOk(ctx, "上传成功", result as UTSJSONObject, payload);
});
}