Upload files to Firebase Storage using Node.js

前端 未结 6 677
情书的邮戳
情书的邮戳 2020-11-27 14:02

I\'m trying to understand how to upload files in Firebase Storage, using Node.js. My first try was to use the Firebase library:

"use strict";

var f         


        
6条回答
  •  孤街浪徒
    2020-11-27 14:22

    I hope It will useful for you. I uploaded one file from locally and then I added access Token using UUID after that I uploaded into firebase storage.There after I am generating download url. If we hitting that generate url it will automatically downloaded a file.

        const keyFilename="./xxxxx.json"; //replace this with api key file
        const projectId = "xxxx" //replace with your project id
        const bucketName = "xx.xx.appspot.com"; //Add your bucket name
        var mime=require('mime-types');
        const { Storage } = require('@google-cloud/storage');
        const uuidv1 = require('uuid/v1');//this for unique id generation
    
       const gcs = new Storage({
        projectId: projectId,
        keyFilename: './xxxx.json'
         });
        const bucket = gcs.bucket(bucketName);
    
        const filePath = "./sample.odp";
        const remotePath = "/test/sample.odp";
        const fileMime = mime.lookup(filePath);
    
    //we need to pass those parameters for this function
        var upload = (filePath, remoteFile, fileMime) => {
    
          let uuid = uuidv1();
    
          return bucket.upload(filePath, {
                destination: remoteFile,
                uploadType: "media",
                metadata: {
                  contentType: fileMime,
                  metadata: {
                    firebaseStorageDownloadTokens: uuid
                  }
                }
              })
              .then((data) => {
    
                  let file = data[0];
    
                  return Promise.resolve("https://firebasestorage.googleapis.com/v0/b/" + bucket.name + "/o/" + encodeURIComponent(file.name) + "?alt=media&token=" + uuid);
              });
        }
    //This function is for generation download url    
     upload(filePath, remotePath, fileMime).then( downloadURL => {
            console.log(downloadURL);
    
          });
    

提交回复
热议问题