Getting the file in busboy to upload to firebase storage

Viewed 596

I am using busboy in node to upload a file to the firebase storage. But everytme i send the post request with a file, it says..

{
    "e": {
        "code_": "storage/invalid-argument",
        "message_": "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.",
        "serverResponse_": null,
        "name_": "FirebaseError"
    }
}

I can't figure out how do i send the file using busboy.. My code snippet is..

    export const uploadAvatar = (req: any, res: any) => {


    const busboy = new BusBoy({ headers: req.headers });
    let filepath: any;
    let imgToBeUploaded: any;
    busboy.on(
        'file',
        (
            fieldname: string,
            file: any,
            filename: string,
            encoding: string,
            mimetype: string
        ) => {
            if (mimetype !== 'image/jpeg' && mimetype !== 'image/png') {
                res.status(400).json({
                    error: 'Wrong image format',
                });
            }

            const imgExt: string = filename.split('.')[
                filename.split('.').length - 1
            ];
            const imgName = `avatar_${req.user.userName}.${imgExt}`;
            filepath = path.join(os.tmpdir(), imgName);
            // modifiedUrl = `avatar_${req.user.userName}_200x200.${imgExt}`;
            file.pipe(fs.createWriteStream(filepath));
            imgToBeUploaded = { filepath, mimetype, file };
        }
    );
    busboy.on('finish', async () => {
        const storageRef = storage.ref();
        try {
            const uploadTask = await storageRef.put(imgToBeUploaded.filepath);
            console.log(`UploadTask : ${uploadTask}`);
            return res.json('File uploaded');
        } catch (e) {
            return res.status(400).json({ e });
        }
});
    busboy.end(req.rawBody);


};

The console.log of 'file' returns the location in tempdir, where the file is stored... Please help me figure out how do i get busboy to return the file, which i can pass to the storageRef.put() 's argument.

0 Answers
Related