上传的文件自动删除

This commit is contained in:
Jerry 2025-05-12 13:58:14 +08:00
parent c1199e1649
commit 27e25d9258
2 changed files with 31 additions and 9 deletions

View File

@ -54,13 +54,14 @@ class FileController {
};
/**
*
* @example
*
* `multipart/form-data` `file`
* @example 使 axios form-data
* ```js
* const form = new FormData();
* const fileStream = fs.createReadStream(filePath);
* form.append('file', fileStream);
* const uploadUrl = `http://localhost:4000/upload?dir=${uploadDir}`;
* const uploadUrl = `http://localhost:4000/upload?dir=example&expire=600`;
* const response = await axios.post(uploadUrl, form, {
* headers: {
* ...form.getHeaders(),
@ -69,6 +70,9 @@ class FileController {
* maxBodyLength: Infinity,
* });
* ```
*
* @queryParam dir
* @queryParam expire 600
* @param req
* @param res
*/
@ -80,10 +84,12 @@ class FileController {
}
const uploadDir = req.query.dir?.toString() || '';
const deleteAfter = parseInt(req.query.expire as string) || 10 * 60;
const { fullPath, relativePath } = await this.FileService.saveUploadedFile(
req.file,
uploadDir
);
await this.FileService.scheduleDelete(fullPath, deleteAfter * 1000);
await response.success(res, {
message: '文件上传成功..',
filePath: fullPath,

View File

@ -52,6 +52,22 @@ class FileService {
};
}
/**
*
* @param filePath
* @param timeoutMs 10
*/
public async scheduleDelete(filePath: string, timeoutMs: number = 10 * 60 * 1000): Promise<void> {
setTimeout(async () => {
try {
await fs.unlink(filePath);
logger.info(`已自动删除文件: ${filePath}`);
} catch (err) {
logger.warn(`删除文件失败: ${filePath}`, err);
}
}, timeoutMs);
}
/**
*
* @param relativePath