2

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.

Rupayan
  • 403
  • 4
  • 8

1 Answers1

1

For anyone who's here looking for an answer... I've had this problem for over a week now. Kept getting Error: TypeError: Cannot read properties of undefined (reading 'byteLength'). Try doing

storageRef.put(fs.readFileSync(imgToBeUploaded.filepath))

It will actually read the data into a buffer from the temporary file on your local computer and send it on to firestore.

Also it might help to console.log your fs.statSync(imgToBeUploaded.filepath) to make sure the file is actually written. Check the size to make sure it's in the expected range for your image.