mirror of
https://gitcode.com/gh_mirrors/hy/Hydro.git
synced 2026-10-17 09:36:08 +08:00
framework: auto cleanup uploaded files (#818)
This commit is contained in:
10 files changed
+40
-24
No files matched your search
@@ -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);
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user