class FileUploader {
FileUploader() {}
async uploadFile(req: Request, res: Response) {
let data: any = {
files: []
}
let form: any = new Formidable.IncomingForm({
multiples: true,
keepExtensions: true,
uploadDir: uploadDir
})
form.on("fileBegin", (name: string, file: any) => {
const [fileName, fileExt] = file.name.split(".");
const newFileName = `${fileName}_${new Date().getTime()}.${fileExt}`;
data.files.push(newFileName);
file.path = path.join(uploadDir, newFileName);
})
form.parse(req, async (err, fields, files) => {
try {
//get other fields
data = {
...data,
...fields
};
if (err) return res.status(500).json({
error: err
});
return res.status(200).json({
success: true,
data
})
} catch (error) {
res.json({
success: false,
error: "Error occured"
})
}
});
}
}
Top comments (0)