framework: auto cleanup uploaded files (#818)

This commit is contained in:
undefined committed 2025-01-03 01:01:37 +08:00
1 parent 8eed68e78f
commit 566ebd9bb2
10 files changed
+40 -24

No files matched your search

+19
View File
@@ -86,6 +86,7 @@ export type KoaContext = Koa.Context & {
handler: any;
request: Koa.Request & { body: any, files: Files };
session: Record<string, any>;
holdFiles: (string | File)[];
};
const logger = new Logger('server');
@@ -199,6 +200,10 @@ export class Handler extends HandlerCommon {
if (name) this.response.disposition = `attachment; filename="${encodeRFC5987ValueChars(name)}"`;
}
holdFile(name: string | File) {
this.context.holdFiles.push(name);
}
async init() {
if (this.request.method === 'post' && this.request.headers.referer && !this.context.cors && !this.allowCors) {
try {
@@ -394,6 +399,20 @@ ${c.response.status} ${endTime - startTime}ms ${c.response.length}`);
keepExtensions: true,
},
}));
this.server.use(async (c, next) => {
c.holdFiles = [];
try {
await next();
} finally {
if (Object.keys(c.request.files || {}).length) {
for (const k in c.request.files) {
if (c.holdFiles.includes(k)) continue;
const files = Array.isArray(c.request.files[k]) ? c.request.files[k] : [c.request.files[k]];
for (const f of files) if (!c.holdFiles.includes(f as any)) fs.rmSync(f.filepath);
}
}
}
});
this.ctx.on('dispose', () => {
fs.emptyDirSync(uploadDir);
});