DEV Community

Cover image for FileUpload in node-ts using formidable module
Gervais Ishimwe
Gervais Ishimwe

Posted on

FileUpload in node-ts using formidable module

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"
            })
        }
    });

}
Enter fullscreen mode Exit fullscreen mode

}

Alt Text

Top comments (0)