Files type image

Use Case

I've been trying to handle POSTs (multipart/form-data) with a Firebase function and Express but it just doesn't work. Tried this in local server and it works just fine. Everything's the same except it's not contained in a Firebase function.

Answer

If you want to create an upload image endpoint inside Google Firebase (Cloud functions), then here is one way you can do it.

const path = require('path');
const Busboy = require('busboy');
const FormData = require('form-data');
const myData = new FormData();


exports.uploadFile = async(req,res)=> {
      const busboy = Busboy({headers: req.headers});
      const fields = {};
      busboy.on('field', (fieldname, val) => {
        console.log(`Processed field ${fieldname}: ${val}.`);
        fields[fieldname] = val;
        myData.append(fieldname, val);
      });
    
      busboy.on("file", (fieldname, file, {filename}, encoding, mimetype) => {
        let parts = {filename}.filename.split(".");
        let name = parts[0];
        let extension = parts[parts.length - 1]; // get extension

        let finalName = `${name}-${+new Date()}.${extension}`;

        myData.append('files', file,finalName);
        file.on('data', function(data) {
          console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
      });
      file.on('end', function () {
        console.log('File [' + fieldname + '] Finished');
    });      

      });
    
      busboy.on('finish', function() {
          console.log('finish');
          return res.status(200).send(myData);
      });
          busboy.end(req.rawBody);
}

Last updated

Was this helpful?