Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

javascript - How to create Firebase storage object from Firebase storage url

When a file is upload to Firebase Storage, you can access an object representing the file in a Firebase Cloud Function via the storage.object().onFinalize() event. This object provides properties such as bucket and name.

For example, you might set up the following to access the file when it is created:

exports.generateThumbnails = functions
    .storage.object()
    .onFinalize(async fileOjbect => {
  // Do something here with the storage object (here named fileObject).
});

My question regards how to get that same object via the object storage url of the form:

gs://my-app.appspot.com/photos/new_photo_here.jpeg

I'm having trouble finding the documentation for creating the object from the url. I would like to pass the url to a constructor of some sort that returns the object so I can then access the bucket and name properties (without having to do any parsing on my own). Does such a constructor exist? If so where is it documented? Something like this:

const file = storage.object('gs://my-app.appspot.com/photos/new_photo_here.jpeg');
question from:https://stackoverflow.com/questions/65642526/how-to-create-firebase-storage-object-from-firebase-storage-url

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use firebase-admin to get storage object from URL. First, you should parse the bucket name from the URL inside your function. Bucket name is followed by gs:// in the URL. Then the next session will be file path, and you can use Bucket object of firebase-admin to get storage object from this file path.

const admin = require('firebase-admin');

function getFirebaseStorageObject(url) {
 const bucketName = url.match(/gs://([^/]*)//)[1]
 const filePath = url.replace(`gs://${bucketName}/`, '')
 
 return admin.storage().bucket(bucketName).file(filePath);
}

getFirebaseStorageObject('gs://my-app.appspot.com/photos/new_photo_here.jpeg');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...