检查一下有没有加Sync
mkdirSync,copyFileSync,unlinkSync
问题代码:
@Controller('/upload')
export class UploadController {
@Post('/')
async uploadFile(@Files() files: any[], ctx: Context) {
if (files && files.length > 0) {
const file = files[0];
console.log(file);
const tempPath = file.data; // 临时路径
const originalFilename = file.filename;
const targetPath = join(
__dirname,
'../../public/uploads',
originalFilename
);
// 确保目标目录存在
fs.mkdir(dirname(targetPath), { recursive: true });
// 移动文件到目标目录,移动完临时文件就会消失
fs.copyFile(tempPath, targetPath);
// 删除临时文件
fs.unlink(tempPath);
return {
success: true,
message: '文件上传成功',
data: { filePath: targetPath },
};
} else {
console.log(3);
return {
success: false,
message: '没有上传文件',
data: '没有上传文件',
};
}
}
}
已解决代码
@Controller('/upload')
export class UploadController {
@Post('/')
async uploadFile(@Files() files: any[], ctx: Context) {
if (files && files.length > 0) {
const file = files[0];
console.log(file);
const tempPath = file.data; // 临时路径
const originalFilename = file.filename;
const targetPath = join(
__dirname,
'../../public/uploads',
originalFilename
);
// 确保目标目录存在
fs.mkdirSync(dirname(targetPath), { recursive: true });
// 移动文件到目标目录,移动完临时文件就会消失
fs.copyFileSync(tempPath, targetPath);
// 删除临时文件
fs.unlinkSync(tempPath);
return {
success: true,
message: '文件上传成功',
data: { filePath: targetPath },
};
} else {
console.log(3);
return {
success: false,
message: '没有上传文件',
data: '没有上传文件',
};
}
}
}