上传的文件自动删除

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,21 +54,25 @@ class FileController {
}; };
/** /**
* *
* @example * `multipart/form-data` `file`
* @example 使 axios form-data
* ```js * ```js
* const form = new FormData(); * const form = new FormData();
* const fileStream = fs.createReadStream(filePath); * const fileStream = fs.createReadStream(filePath);
* form.append('file', fileStream); * 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, { * const response = await axios.post(uploadUrl, form, {
* headers: { * headers: {
* ...form.getHeaders(), * ...form.getHeaders(),
* }, * },
* maxContentLength: Infinity, * maxContentLength: Infinity,
* maxBodyLength: Infinity, * maxBodyLength: Infinity,
* }); * });
* ``` * ```
*
* @queryParam dir
* @queryParam expire 600
* @param req * @param req
* @param res * @param res
*/ */
@ -80,10 +84,12 @@ class FileController {
} }
const uploadDir = req.query.dir?.toString() || ''; const uploadDir = req.query.dir?.toString() || '';
const deleteAfter = parseInt(req.query.expire as string) || 10 * 60;
const { fullPath, relativePath } = await this.FileService.saveUploadedFile( const { fullPath, relativePath } = await this.FileService.saveUploadedFile(
req.file, req.file,
uploadDir uploadDir
); );
await this.FileService.scheduleDelete(fullPath, deleteAfter * 1000);
await response.success(res, { await response.success(res, {
message: '文件上传成功..', message: '文件上传成功..',
filePath: fullPath, 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 * @param relativePath