file-handle 0.0.7 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/README.zh-CN.md +2 -2
- package/package.json +1 -1
- package/server/bin/cli.js +1 -1
- package/server/bin/fork.js +18 -11
- package/server/common/adapter.js +7 -6
- package/server/common/i18n.js +3 -3
- package/server/config.js +3 -1
- package/server/fh.app.dat +0 -0
- package/server/index.js +21 -20
- package/server/middlewares/upload.js +159 -8
- package/server/routes/api.js +38 -11
- package/server/routes/fh.js +3 -1
- package/server/routes/res.js +3 -2
- package/server/utils/Preview/Markdown/registrie.js +1 -1
- package/server/utils/Preview/Text/registrie.js +1 -1
package/README.md
CHANGED
package/README.zh-CN.md
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "file-handle",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.1.0",
|
|
4
4
|
"author": "jsonhandle@gmail.com",
|
|
5
5
|
"description": "A simple local web file server with a user-friendly interface, allowing easy file upload, download, preview, and management through a browser. \n一个简易的文件服务器,方便通过浏览器来浏览、上传或管理目录和文件. ",
|
|
6
6
|
"main": "server/index.js",
|
package/server/bin/cli.js
CHANGED
package/server/bin/fork.js
CHANGED
|
@@ -4,20 +4,27 @@ import path from 'path';
|
|
|
4
4
|
import { loadConfig } from '../config.js';
|
|
5
5
|
import Debug from 'debug';
|
|
6
6
|
const debug = Debug('FH fork');
|
|
7
|
+
const isDevelopment = process.env.NODE_ENV?.trim() === 'development';
|
|
7
8
|
process.on('message', (msg) => {
|
|
8
9
|
startServer(JSON.parse(msg.opt));
|
|
9
10
|
});
|
|
10
11
|
export function start(config) {
|
|
11
12
|
const env = loadConfig({ rootDir: process.cwd() });
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
13
|
+
debug('isDevelopment:', env.isDevelopment);
|
|
14
|
+
if (env.isDevelopment) {
|
|
15
|
+
startServer(config);
|
|
16
|
+
}
|
|
17
|
+
else {
|
|
18
|
+
const forkEnter = path.join(env.mdDir, './bin/fork.js');
|
|
19
|
+
const child = fork(forkEnter, [], {
|
|
20
|
+
execArgv: ['--title=File-Handle-Server']
|
|
21
|
+
});
|
|
22
|
+
child.on('message', (msg) => {
|
|
23
|
+
debug('child:', msg);
|
|
24
|
+
});
|
|
25
|
+
child.send({ opt: JSON.stringify(config) });
|
|
26
|
+
child.on('exit', (code) => {
|
|
27
|
+
debug(`FH exited with code ${code}`);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
23
30
|
}
|
package/server/common/adapter.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { createProxyMiddleware } from 'http-proxy-middleware';
|
|
2
2
|
import { resolve } from 'path';
|
|
3
|
-
import
|
|
3
|
+
import Debug from 'debug';
|
|
4
4
|
import mime from 'mime-types';
|
|
5
5
|
import unzip from 'unzipper';
|
|
6
|
-
const
|
|
6
|
+
const debug = Debug('FH adapter');
|
|
7
7
|
let resMap;
|
|
8
8
|
export function buildPreviewerHtml(html) {
|
|
9
9
|
const modifiedBody = html.replace('<base id="baseUrl" />', `<base id="baseUrl" href="/fh/" />`);
|
|
@@ -13,8 +13,9 @@ export async function sendFeReq(uri, req, res, next, sendBefore) {
|
|
|
13
13
|
const config = global.config;
|
|
14
14
|
// 获取node入口目录的绝对路径
|
|
15
15
|
const fhDir = config.mdDir;
|
|
16
|
+
debug('isDevelopment:', config.isDevelopment);
|
|
16
17
|
debug('sendFeReq uri: ' + uri + ' | path: ' + req.path);
|
|
17
|
-
if (!isDevelopment && !resMap) {
|
|
18
|
+
if (!config.isDevelopment && !resMap) {
|
|
18
19
|
resMap = await getRes(resolve(fhDir, './fh.app.dat'));
|
|
19
20
|
}
|
|
20
21
|
const bCb = !!sendBefore;
|
|
@@ -25,12 +26,12 @@ export async function sendFeReq(uri, req, res, next, sendBefore) {
|
|
|
25
26
|
changeOrigin: true,
|
|
26
27
|
ws: true,
|
|
27
28
|
pathRewrite: {
|
|
28
|
-
'^.*': '/res' + req.url
|
|
29
|
+
'^.*': '/___file-handle___/res' + req.url
|
|
29
30
|
}
|
|
30
31
|
};
|
|
31
32
|
if ({}.toString.call(uri) == '[object String]') {
|
|
32
33
|
opt.pathRewrite = {
|
|
33
|
-
'^.*': '/res/' + uri
|
|
34
|
+
'^.*': '/___file-handle___/res/' + uri
|
|
34
35
|
};
|
|
35
36
|
resFilePath = uri;
|
|
36
37
|
}
|
|
@@ -61,7 +62,7 @@ export async function sendFeReq(uri, req, res, next, sendBefore) {
|
|
|
61
62
|
}
|
|
62
63
|
};
|
|
63
64
|
}
|
|
64
|
-
if (isDevelopment) {
|
|
65
|
+
if (config.isDevelopment) {
|
|
65
66
|
createProxyMiddleware(opt)(req, res, next);
|
|
66
67
|
}
|
|
67
68
|
else {
|
package/server/common/i18n.js
CHANGED
|
@@ -42,9 +42,9 @@ const i18n = {
|
|
|
42
42
|
switchLang: '切换到中文'
|
|
43
43
|
},
|
|
44
44
|
server: {
|
|
45
|
-
startingHttps: 'Starting FH
|
|
46
|
-
startingHttp: 'Starting FH
|
|
47
|
-
running: 'File-Handle Server is running on port',
|
|
45
|
+
startingHttps: 'Starting FH HTTPS server...',
|
|
46
|
+
startingHttp: 'Starting FH HTTP server...',
|
|
47
|
+
running: 'File-Handle Server is running on port: ',
|
|
48
48
|
rootDirectory: 'Root directory:',
|
|
49
49
|
accessibleAddresses: 'Accessible addresses:',
|
|
50
50
|
allowedIpsOnly: 'Only allowed IPs can access',
|
package/server/config.js
CHANGED
|
@@ -28,6 +28,7 @@ global.config = global.config || {
|
|
|
28
28
|
writeLog: false,
|
|
29
29
|
uploadLimit: parseFileSize('3GB'),
|
|
30
30
|
allowWan: false,
|
|
31
|
+
isDevelopment: false,
|
|
31
32
|
ipList: ['127.0.0.1']
|
|
32
33
|
};
|
|
33
34
|
export function loadConfig(opt) {
|
|
@@ -42,8 +43,9 @@ export function loadConfig(opt) {
|
|
|
42
43
|
if (opt.password === '') {
|
|
43
44
|
opt.password = createRandomPassword(16);
|
|
44
45
|
}
|
|
46
|
+
opt.isDevelopment = opt.isDevelopment || process.env.NODE_ENV?.trim() === 'development';
|
|
45
47
|
global.config = opt;
|
|
46
|
-
createAppKey(global.config);
|
|
48
|
+
// createAppKey(global.config);
|
|
47
49
|
return opt;
|
|
48
50
|
}
|
|
49
51
|
export function getAppKeyPath() {
|
package/server/fh.app.dat
CHANGED
|
Binary file
|
package/server/index.js
CHANGED
|
@@ -34,18 +34,15 @@ export async function startServer(opt) {
|
|
|
34
34
|
next();
|
|
35
35
|
});
|
|
36
36
|
// app.use(corsMiddleware);
|
|
37
|
-
app.use('/app', createAppRouter(config));
|
|
38
37
|
app.use(validateIpAccess(config));
|
|
39
38
|
app.use(validatePassword(config));
|
|
40
39
|
app.use(validateFileOperation(config));
|
|
41
|
-
// 根路径重定向到文件系统
|
|
42
|
-
app.get('/', (req, res) => {
|
|
43
|
-
res.redirect('/fh/');
|
|
44
|
-
});
|
|
45
40
|
// 配置路由
|
|
46
|
-
app.use('/
|
|
47
|
-
app.use('/api', createApiRouter(config));
|
|
41
|
+
app.use('/___file-handle___/app', createAppRouter(config));
|
|
42
|
+
app.use('/___file-handle___/api', createApiRouter(config));
|
|
48
43
|
createResourcesRouter(app, config);
|
|
44
|
+
// 根到文件系统
|
|
45
|
+
app.get(/^\/(?!___file-handle___)/, createFileSystemRouter(config));
|
|
49
46
|
// 错误处理
|
|
50
47
|
app.use(handleUploadError);
|
|
51
48
|
app.use(errorHandler);
|
|
@@ -63,6 +60,10 @@ export async function startServer(opt) {
|
|
|
63
60
|
server = http.createServer(app);
|
|
64
61
|
info(lang.server.startingHttp);
|
|
65
62
|
}
|
|
63
|
+
// 大文件上传可能耗时较长,关闭服务器端的请求/连接超时,
|
|
64
|
+
// 避免上传过程中被 Node 默认超时(requestTimeout 默认 5 分钟)截断
|
|
65
|
+
server.timeout = 0; // 关闭 socket 空闲超时(默认即 0,显式声明)
|
|
66
|
+
server.requestTimeout = 0; // 关闭整体请求超时(默认 5 分钟,大文件会被截断)
|
|
66
67
|
const port = await findAvailablePort(config.port);
|
|
67
68
|
const localIPs = getLocalNetworkIPs();
|
|
68
69
|
global.config.port = port;
|
|
@@ -71,12 +72,12 @@ export async function startServer(opt) {
|
|
|
71
72
|
// 如果指定了允许访问的IP地址,则只允许这些IP访问
|
|
72
73
|
server.once('listening', () => resolve(global.config)).listen(port, '0.0.0.0', () => {
|
|
73
74
|
info(lang.server.allowedIpsOnly);
|
|
74
|
-
info(`${lang.server.running}${color.blueBright(port)}`);
|
|
75
|
-
info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
|
|
75
|
+
info(`${lang.server.running} ${color.blueBright(port)}`);
|
|
76
|
+
info(`${lang.server.rootDirectory} ${color.yellow(config.rootDir)}`);
|
|
76
77
|
info(lang.server.accessibleAddresses);
|
|
77
|
-
info(color.green(`http://127.0.0.1:${port}
|
|
78
|
+
info(color.green(`http://127.0.0.1:${port}/`));
|
|
78
79
|
config.allowedIPs && config.allowedIPs.forEach(ip => {
|
|
79
|
-
info(color.green(`http://${ip}:${port}
|
|
80
|
+
info(color.green(`http://${ip}:${port}/`));
|
|
80
81
|
config.ipList?.push(ip);
|
|
81
82
|
});
|
|
82
83
|
info('\n\n');
|
|
@@ -86,12 +87,12 @@ export async function startServer(opt) {
|
|
|
86
87
|
// 如果存在局域网IP且未启用公网访问,则只监听局域网IP
|
|
87
88
|
server.once('listening', () => resolve(global.config)).listen(port, '0.0.0.0', () => {
|
|
88
89
|
info(lang.server.localAndLanOnly);
|
|
89
|
-
info(`${lang.server.running}${color.blueBright(port)}`);
|
|
90
|
-
info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
|
|
90
|
+
info(`${lang.server.running} ${color.blueBright(port)}`);
|
|
91
|
+
info(`${lang.server.rootDirectory} ${color.yellow(config.rootDir)}`);
|
|
91
92
|
info(lang.server.accessibleAddresses);
|
|
92
|
-
info(color.green(`http://127.0.0.1:${port}
|
|
93
|
+
info(color.green(`http://127.0.0.1:${port}/`));
|
|
93
94
|
localIPs.forEach(ip => {
|
|
94
|
-
info(color.green(`http://${ip}:${port}
|
|
95
|
+
info(color.green(`http://${ip}:${port}/`));
|
|
95
96
|
config.ipList?.push(ip);
|
|
96
97
|
});
|
|
97
98
|
info('\n\n');
|
|
@@ -100,11 +101,11 @@ export async function startServer(opt) {
|
|
|
100
101
|
else {
|
|
101
102
|
// 允许所有IP访问
|
|
102
103
|
server.once('listening', () => resolve(global.config)).listen(port, '0.0.0.0', () => {
|
|
103
|
-
info(`${lang.server.running}${color.blueBright(port)}`);
|
|
104
|
-
info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
|
|
104
|
+
info(`${lang.server.running} ${color.blueBright(port)}`);
|
|
105
|
+
info(`${lang.server.rootDirectory} ${color.yellow(config.rootDir)}`);
|
|
105
106
|
info(lang.server.accessibleAddresses);
|
|
106
|
-
info(`http://0.0.0.0:${port}
|
|
107
|
-
info(color.green(`http://127.0.0.1:${port}
|
|
107
|
+
info(`http://0.0.0.0:${port}/`);
|
|
108
|
+
info(color.green(`http://127.0.0.1:${port}/`));
|
|
108
109
|
localIPs.forEach(ip => {
|
|
109
110
|
config.ipList?.push(ip);
|
|
110
111
|
});
|
|
@@ -112,7 +113,7 @@ export async function startServer(opt) {
|
|
|
112
113
|
});
|
|
113
114
|
}
|
|
114
115
|
if (config.password) {
|
|
115
|
-
info(`${lang.server.loginPassword}${color.green(config.password)}`);
|
|
116
|
+
info(`${lang.server.loginPassword} ${color.green(config.password)}`);
|
|
116
117
|
}
|
|
117
118
|
}).then(_ => {
|
|
118
119
|
// 对ipList进行去重
|
|
@@ -1,15 +1,145 @@
|
|
|
1
1
|
import multer from 'multer';
|
|
2
2
|
import path from 'path';
|
|
3
|
-
import
|
|
3
|
+
import fs from 'fs/promises';
|
|
4
|
+
import { validateFileName, normalizePath } from '../utils/path.js';
|
|
4
5
|
import { FileOperationError } from '../types/index.js';
|
|
5
6
|
import { debug, error } from '../utils/logger.js';
|
|
7
|
+
// 内存中的上传会话表(uploadId -> session)
|
|
8
|
+
const uploadSessions = new Map();
|
|
9
|
+
export function getUploadSession(uploadId) {
|
|
10
|
+
return uploadSessions.get(uploadId);
|
|
11
|
+
}
|
|
12
|
+
// 解析客户端通过 header 传入的预期文件大小清单(x-upload-meta)
|
|
13
|
+
// 格式:encodeURIComponent(JSON.stringify([{ name, size }, ...]))
|
|
14
|
+
function parseExpectedMeta(req) {
|
|
15
|
+
const header = req.headers['x-upload-meta'];
|
|
16
|
+
if (!header)
|
|
17
|
+
return new Map();
|
|
18
|
+
try {
|
|
19
|
+
const json = JSON.parse(decodeURIComponent(header));
|
|
20
|
+
const map = new Map();
|
|
21
|
+
if (Array.isArray(json)) {
|
|
22
|
+
for (const item of json) {
|
|
23
|
+
if (item && item.name !== undefined && typeof item.size === 'number') {
|
|
24
|
+
map.set(item.name, item.size);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return map;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return new Map();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
// 跟踪上传进度的中间件:统计已接收字节,写入会话表供状态接口查询
|
|
35
|
+
// 仅作用于上传路由,需在 multer 之前挂载
|
|
36
|
+
export function trackUpload(req, res, next) {
|
|
37
|
+
const uploadId = req.headers['x-upload-id'] || '';
|
|
38
|
+
if (uploadId) {
|
|
39
|
+
const total = Number(req.headers['content-length'] || 0) || 0;
|
|
40
|
+
const filenameHeader = req.headers['x-upload-filename'];
|
|
41
|
+
const filename = filenameHeader ? decodeURIComponent(filenameHeader) : '';
|
|
42
|
+
const session = {
|
|
43
|
+
uploadId,
|
|
44
|
+
filename,
|
|
45
|
+
received: 0,
|
|
46
|
+
total,
|
|
47
|
+
done: false,
|
|
48
|
+
error: null,
|
|
49
|
+
startedAt: Date.now(),
|
|
50
|
+
};
|
|
51
|
+
uploadSessions.set(uploadId, session);
|
|
52
|
+
// 统计流入字节('data' 监听不会阻止 busboy/multer 消费流)
|
|
53
|
+
req.on('data', (chunk) => {
|
|
54
|
+
session.received += chunk.length;
|
|
55
|
+
});
|
|
56
|
+
// 请求异常中断
|
|
57
|
+
req.on('aborted', () => {
|
|
58
|
+
if (!session.error)
|
|
59
|
+
session.error = 'aborted';
|
|
60
|
+
});
|
|
61
|
+
req.on('error', (err) => {
|
|
62
|
+
if (!session.error)
|
|
63
|
+
session.error = err.message || 'request error';
|
|
64
|
+
});
|
|
65
|
+
// 响应关闭(成功/失败/中断均触发):标记完成,延时清理会话
|
|
66
|
+
res.on('close', () => {
|
|
67
|
+
session.done = true;
|
|
68
|
+
if (!session.error && req.aborted) {
|
|
69
|
+
session.error = 'aborted';
|
|
70
|
+
}
|
|
71
|
+
setTimeout(() => {
|
|
72
|
+
uploadSessions.delete(uploadId);
|
|
73
|
+
}, 60000);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
next();
|
|
77
|
+
}
|
|
78
|
+
// 校验并清理不完整的上传文件
|
|
79
|
+
// 比对每个已开始写入的文件实际大小与客户端声明的预期大小;
|
|
80
|
+
// 不一致或缺失则删除残留,返回完整文件列表与被清理的文件名
|
|
81
|
+
export async function verifyAndCleanupUploads(req) {
|
|
82
|
+
const expected = parseExpectedMeta(req);
|
|
83
|
+
const started = req._uploadStarted || [];
|
|
84
|
+
const files = [];
|
|
85
|
+
const incomplete = [];
|
|
86
|
+
for (const f of started) {
|
|
87
|
+
let size = -1;
|
|
88
|
+
try {
|
|
89
|
+
const stat = await fs.stat(f.path);
|
|
90
|
+
size = stat.size;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
size = -1;
|
|
94
|
+
}
|
|
95
|
+
const expectedSize = expected.get(f.originalName);
|
|
96
|
+
if (expectedSize !== undefined && size !== expectedSize) {
|
|
97
|
+
// 大小不符:上传不完整,删除残留
|
|
98
|
+
try {
|
|
99
|
+
await fs.unlink(f.path);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
// 删除失败忽略(文件可能已不存在)
|
|
103
|
+
}
|
|
104
|
+
incomplete.push(f.originalName);
|
|
105
|
+
}
|
|
106
|
+
else if (size < 0) {
|
|
107
|
+
// 文件不存在:记为不完整
|
|
108
|
+
incomplete.push(f.originalName);
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
files.push({ originalName: f.originalName, savedPath: f.path, size });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return { files, incomplete };
|
|
115
|
+
}
|
|
6
116
|
// 创建文件上传配置
|
|
7
117
|
export function createUploadMiddleware(config) {
|
|
8
118
|
const storage = multer.diskStorage({
|
|
9
119
|
destination: (req, file, cb) => {
|
|
10
|
-
//
|
|
11
|
-
|
|
12
|
-
|
|
120
|
+
// 优先使用客户端显式传入的目标目录(?path=)
|
|
121
|
+
let uploadPath = req.query.path || '';
|
|
122
|
+
// 兼容未显式传 path 的调用:从 referer 中提取路径名,避免把完整 URL 当目录
|
|
123
|
+
if (!uploadPath) {
|
|
124
|
+
const referer = req.headers.referer;
|
|
125
|
+
if (referer) {
|
|
126
|
+
try {
|
|
127
|
+
uploadPath = decodeURIComponent(new URL(referer).pathname);
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
uploadPath = referer;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
// 规范化并校验路径必须位于根目录内(防止路径穿越)
|
|
135
|
+
let targetDir;
|
|
136
|
+
try {
|
|
137
|
+
targetDir = normalizePath(uploadPath || '/', config.rootDir);
|
|
138
|
+
}
|
|
139
|
+
catch (err) {
|
|
140
|
+
return cb(err, '');
|
|
141
|
+
}
|
|
142
|
+
req._uploadDir = targetDir;
|
|
13
143
|
cb(null, targetDir);
|
|
14
144
|
},
|
|
15
145
|
filename: (req, file, cb) => {
|
|
@@ -21,6 +151,13 @@ export function createUploadMiddleware(config) {
|
|
|
21
151
|
// 如果文件已存在,添加时间戳
|
|
22
152
|
const filename = decodedName;
|
|
23
153
|
debug(`Processing upload: ${filename}`);
|
|
154
|
+
// 记录已开始写入的文件路径,便于中断后校验与清理残留
|
|
155
|
+
const dir = req._uploadDir;
|
|
156
|
+
if (dir) {
|
|
157
|
+
if (!req._uploadStarted)
|
|
158
|
+
req._uploadStarted = [];
|
|
159
|
+
req._uploadStarted.push({ originalName: decodedName, path: path.join(dir, filename) });
|
|
160
|
+
}
|
|
24
161
|
cb(null, filename);
|
|
25
162
|
}
|
|
26
163
|
});
|
|
@@ -43,15 +180,29 @@ export function createUploadMiddleware(config) {
|
|
|
43
180
|
}
|
|
44
181
|
});
|
|
45
182
|
}
|
|
46
|
-
//
|
|
47
|
-
|
|
183
|
+
// 错误处理中间件(含上传中断/超限等)
|
|
184
|
+
// 任何上传错误都先清理不完整的残留文件,再返回错误响应
|
|
185
|
+
export async function handleUploadError(err, req, res, next) {
|
|
186
|
+
// 清理不完整上传残留(对非上传请求为空操作)
|
|
187
|
+
try {
|
|
188
|
+
await verifyAndCleanupUploads(req);
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
// 清理失败不应影响错误响应
|
|
192
|
+
}
|
|
48
193
|
if (err instanceof multer.MulterError) {
|
|
49
194
|
if (err.code === 'LIMIT_FILE_SIZE') {
|
|
50
195
|
return res.status(413).json({
|
|
51
|
-
|
|
52
|
-
|
|
196
|
+
code: -413,
|
|
197
|
+
msg: 'File too large',
|
|
198
|
+
data: null
|
|
53
199
|
});
|
|
54
200
|
}
|
|
201
|
+
return res.status(400).json({
|
|
202
|
+
code: -400,
|
|
203
|
+
msg: err.message,
|
|
204
|
+
data: null
|
|
205
|
+
});
|
|
55
206
|
}
|
|
56
207
|
next(err);
|
|
57
208
|
}
|
package/server/routes/api.js
CHANGED
|
@@ -4,22 +4,49 @@ import path from 'path';
|
|
|
4
4
|
import { ApiResponseBuilder } from '../types/response.js';
|
|
5
5
|
import { normalizePath, validateFileName } from '../utils/path.js';
|
|
6
6
|
import { isEditorAble, isPreviewAble, getMime, extname } from '../types/index.js';
|
|
7
|
-
import { createUploadMiddleware } from '../middlewares/upload.js';
|
|
8
|
-
import { info } from '../utils/logger.js';
|
|
7
|
+
import { createUploadMiddleware, trackUpload, verifyAndCleanupUploads, getUploadSession } from '../middlewares/upload.js';
|
|
8
|
+
import { info, warn } from '../utils/logger.js';
|
|
9
9
|
export function createApiRouter(config) {
|
|
10
10
|
const router = Router();
|
|
11
11
|
const upload = createUploadMiddleware(config);
|
|
12
12
|
// 配置文件上传路由
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
13
|
+
// trackUpload 在 multer 之前挂载,统计已接收字节供 /upload/status 查询
|
|
14
|
+
router.post('/upload', trackUpload, upload.array('files'), async (req, res, next) => {
|
|
15
|
+
try {
|
|
16
|
+
// 上传完成后校验文件完整性,删除不完整残留
|
|
17
|
+
const { files, incomplete } = await verifyAndCleanupUploads(req);
|
|
18
|
+
if (incomplete.length > 0) {
|
|
19
|
+
warn(`Incomplete upload removed: ${incomplete.join(', ')}`);
|
|
20
|
+
return res.json({
|
|
21
|
+
code: -1,
|
|
22
|
+
msg: `Incomplete upload: ${incomplete.join(', ')}`,
|
|
23
|
+
data: { files, incomplete }
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
res.json(ApiResponseBuilder.success({
|
|
27
|
+
files
|
|
28
|
+
}, 'Files uploaded successfully'));
|
|
29
|
+
info(`Uploaded: ${files.length} files`);
|
|
30
|
+
}
|
|
31
|
+
catch (err) {
|
|
32
|
+
next(err);
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
// 查询某次上传的实时进度
|
|
36
|
+
router.get('/upload/status', (req, res) => {
|
|
37
|
+
const uploadId = req.query.uploadId || '';
|
|
38
|
+
const session = uploadId ? getUploadSession(uploadId) : undefined;
|
|
39
|
+
if (!session) {
|
|
40
|
+
return res.json(ApiResponseBuilder.success(null));
|
|
41
|
+
}
|
|
19
42
|
res.json(ApiResponseBuilder.success({
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
43
|
+
uploadId: session.uploadId,
|
|
44
|
+
filename: session.filename,
|
|
45
|
+
received: session.received,
|
|
46
|
+
total: session.total,
|
|
47
|
+
done: session.done,
|
|
48
|
+
error: session.error
|
|
49
|
+
}));
|
|
23
50
|
});
|
|
24
51
|
router.post('/create', async (req, res, next) => {
|
|
25
52
|
try {
|
package/server/routes/fh.js
CHANGED
|
@@ -3,7 +3,7 @@ import { getMime } from '../types/index.js';
|
|
|
3
3
|
import { normalizePath } from '../utils/path.js';
|
|
4
4
|
import { sendFeReq } from "../common/adapter.js";
|
|
5
5
|
import fs from 'fs/promises';
|
|
6
|
-
import { info } from '../utils/logger.js';
|
|
6
|
+
import { debug, info } from '../utils/logger.js';
|
|
7
7
|
import path from 'path';
|
|
8
8
|
import archiver from 'archiver';
|
|
9
9
|
export function createFileSystemRouter(config) {
|
|
@@ -13,6 +13,7 @@ export function createFileSystemRouter(config) {
|
|
|
13
13
|
sendFeReq('index.html', req, res, next);
|
|
14
14
|
};
|
|
15
15
|
router.get('/*', async (req, res, next) => {
|
|
16
|
+
debug('router:/ ');
|
|
16
17
|
try {
|
|
17
18
|
const downloadFlag = req.query.download === 'true';
|
|
18
19
|
const viewFlag = req.query.view;
|
|
@@ -20,6 +21,7 @@ export function createFileSystemRouter(config) {
|
|
|
20
21
|
const requestPath = req.params[0]?.replace(/^fh\//, '') || '';
|
|
21
22
|
const fullPath = normalizePath(requestPath, config.rootDir);
|
|
22
23
|
const stats = await fs.stat(fullPath);
|
|
24
|
+
debug('fullPath: ' + fullPath);
|
|
23
25
|
if (stats.isDirectory()) {
|
|
24
26
|
if (downloadFlag) {
|
|
25
27
|
// 创建zip压缩包
|
package/server/routes/res.js
CHANGED
|
@@ -3,9 +3,10 @@ import { buildPreviewerHtml, sendFeReq } from "../common/adapter.js";
|
|
|
3
3
|
export function createResourcesRouter(app, config) {
|
|
4
4
|
const routerRes = Router();
|
|
5
5
|
routerRes.get('/*', (req, res, next) => {
|
|
6
|
+
debugger;
|
|
6
7
|
sendFeReq(null, req, res, next);
|
|
7
8
|
});
|
|
8
|
-
app.use('/res', routerRes);
|
|
9
|
+
app.use('/___file-handle___/res', routerRes);
|
|
9
10
|
const routerPreview = Router();
|
|
10
11
|
routerPreview.get('/*', (req, res, next) => {
|
|
11
12
|
sendFeReq({
|
|
@@ -14,5 +15,5 @@ export function createResourcesRouter(app, config) {
|
|
|
14
15
|
return buildPreviewerHtml(content);
|
|
15
16
|
});
|
|
16
17
|
});
|
|
17
|
-
app.use('/previewer', routerRes);
|
|
18
|
+
app.use('/___file-handle___/previewer', routerRes);
|
|
18
19
|
}
|