Get Download URL from file uploaded with Cloud Functions for Firebase

后端 未结 23 1787
春和景丽
春和景丽 2020-11-22 01:19

After uploading a file in Firebase Storage with Functions for Firebase, I\'d like to get the download url of the file.

I have this :

...

return buck         


        
23条回答
  •  囚心锁ツ
    2020-11-22 02:05

    Here's an example on how to specify the download token on upload:

    const UUID = require("uuid-v4");
    
    const fbId = "";
    const fbKeyFile = "./YOUR_AUTH_FIlE.json";
    const gcs = require('@google-cloud/storage')({keyFilename: fbKeyFile});
    const bucket = gcs.bucket(`${fbId}.appspot.com`);
    
    var upload = (localFile, remoteFile) => {
    
      let uuid = UUID();
    
      return bucket.upload(localFile, {
            destination: remoteFile,
            uploadType: "media",
            metadata: {
              contentType: 'image/png',
              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);
          });
    }
    

    then call with

    upload(localPath, remotePath).then( downloadURL => {
        console.log(downloadURL);
      });
    

    The key thing here is that there is a metadata object nested within the metadata option property. Setting firebaseStorageDownloadTokens to a uuid-v4 value will tell Cloud Storage to use that as its public auth token.

    Many thanks to @martemorfosis

提交回复
热议问题