2

I have a function which receives a file in this format through multer package.. Now I want to upload this file to firebase storage, for that I need it in a Blob or in javascript file format.

My function is-

const getFileURL = file => {
    const storageRef = firebase.storage().ref();
    let url = "";
    let err = null;
    const metadata = {
        contentType: file.mimetype,
    };
    const uploadFile = storageRef.child(name).put(file);
    uploadFile.on(
        "state_changed",
        function (snapshot) {},
        function (error) {
            console.log("errrroror", error);
            return error;
        },
        function () {
            uploadFile.snapshot.ref
                .getDownloadURL()
                .then(function (downloadURL) {
                    url = downloadURL;
                    return url;
                });
        }
    );
};

File received in the above function:

{
  fieldname: 'file',
  originalname: 'file_name.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: './public/images',
  filename: '85d68e32b2b18adbfc7d0f72b5746e43',
  path: 'public/images/85d68e32b2b18adbfc7d0f72b5746e43',
  size: 96966
}

Caller Function:

uploadImage = async (req, res, next) => {
    try {
        const url = getFileURL(req.files[0]);
        return res.json({ location: url });
    } catch (e) {
        return res.json(e);
    }
}

I'm getting error as :Firebase Storage: Invalid argument in 'put' at index 0: Expected Blob or File.

thatman303
  • 163
  • 6
  • 15

1 Answers1

-1

This should work

// ...snip
const blob = new Blob([file.buffer])
const uploadFile = storageRef.child(name).put(blob)
// ...snip

Reference or this answer

Shivam Singla
  • 2,117
  • 1
  • 10
  • 22
  • Hi, actually 'Blob' function is not defined in Nodejs. So I'm getting error as `ReferenceError: Blob is not defined` – thatman303 Oct 09 '20 at 19:29
  • @YashBoura Try [blob](https://www.npmjs.com/package/blob) for client side or [node-blob](https://www.npmjs.com/package/node-blob) for server side – Shivam Singla Oct 09 '20 at 19:36
  • I want to handle in server side. No luck with node-blob too. – thatman303 Oct 09 '20 at 19:44
  • @YashBoura are the firebase storage API available for server-side too? As far as I know, we have to use google client libraries to upload to firebase storage. [ref](https://firebase.google.com/docs/storage/admin/start#top_of_page) – Shivam Singla Oct 09 '20 at 19:52
  • 1
    Well you are right, I have to use google cloud for this. Thanks – thatman303 Oct 10 '20 at 06:26