Firebase cloud function for file upload

 first thing: var filePath = file.path + "/" + file.name;

Firebase cloud function for file upload

 first thing:

var filePath = file.path + "/" + file.name;

we don't need the file.name since the file.path is the full path of the file (including the file n

ame). So changed it to this instead:

var filePath = file.path;

Second, the function terminates before the asynchronous work in 'form.parse(...)' is completed. That means the actual file upload might still be in progress while the function execution has ended.

The fix for that is to wrap the form.parse(...) in a promise:

exports.uploadFile = functions.https.onRequest((req, res) => {
   var form = new formidable.IncomingForm();
   return new Promise((resolve, reject) => {
     form.parse(req, function(err, fields, files) {
       var file = files.fileToUpload;
       if(!file){
         reject("no file to upload, please choose a file.");
         return;
       }
       console.info("about to upload file as a json: " + file.type);
       var filePath = file.path;
       console.log('File path: ' + filePath);
 
       var bucket = gcs.bucket('bucket-name');
       return bucket.upload(filePath, {
           destination: file.name
       }).then(() => {
         resolve();  // Whole thing completed successfully.
       }).catch((err) => {
         reject('Failed to upload: ' + JSON.stringify(err));
       });
     });
   }).then(() => {
     res.status(200).send('Yay!');
     return null
   }).catch(err => {
     console.error('Error while parsing form: ' + err);
     res.status(500).send('Error while parsing form: ' + err);
   });
 });

Lastly, you may want to consider using Cloud Storage for Firebase in uploading your file instead of Cloud functions. Cloud Storage for Firebase allows you to upload files directly to it, and would work much better:

  1. It has access control
  2. It has resumable uploads/downloads (great for poor connectivity)
  3. It can accept files of any size without timeout-issues
  4. If you want to trigger a Cloud Function on file upload even, you can do that and a lot more