How to get a list of all files in Cloud Storage in a Firebase app?

后端 未结 19 1036
傲寒
傲寒 2020-11-21 11:25

I\'m working on uploading images, everything works great, but I have 100 pictures and I would like to show all of them in my View, as I get the complete list of

相关标签:
19条回答
  • 2020-11-21 12:02

    For node js, I used this code

    const Storage = require('@google-cloud/storage');
    const storage = new Storage({projectId: 'PROJECT_ID', keyFilename: 'D:\\keyFileName.json'});
    const bucket = storage.bucket('project.appspot.com'); //gs://project.appspot.com
    bucket.getFiles().then(results => {
        const files = results[0];
        console.log('Total files:', files.length);
        files.forEach(file => {
          file.download({destination: `D:\\${file}`}).catch(error => console.log('Error: ', error))
        });
    }).catch(err => {
        console.error('ERROR:', err);
      });
    
    0 讨论(0)
  • 2020-11-21 12:02

    To do this with JS

    You can append them directly to your div container, or you can push them to an array. The below shows you how to append them to your div.

    1) When you store your images in storage create a reference to the image in your firebase database with the following structure

    /images/(imageName){
       description: "" , 
       imageSrc : (imageSource) 
    }
    

    2) When you load you document pull all your image source URLs from the database rather than the storage with the following code

    $(document).ready(function(){
    
    var query = firebase.database().ref('images/').orderByKey();
    query.once("value").then(function(snapshot){
    
        snapshot.forEach(function(childSnapshot){
    
            var imageName = childSnapshot.key;
            var childData = childSnapshot.val();
            var imageSource = childData.url;
    
            $('#imageGallery').append("<div><img src='"+imageSource+"'/></div>");
    
        })
    })
    });
    
    0 讨论(0)
  • 2020-11-21 12:02
    #In Python
    
    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import storage
    import datetime
    import urllib.request
    
    
    def image_download(url, name_img) :
        urllib.request.urlretrieve(url, name_img)
    
    cred = credentials.Certificate("credentials.json")
    
    # Initialize the app with a service account, granting admin privileges
    app = firebase_admin.initialize_app(cred, {
        'storageBucket': 'YOURSTORAGEBUCKETNAME.appspot.com',
    })
    url_img = "gs://YOURSTORAGEBUCKETNAME.appspot.com/"
    bucket_1 = storage.bucket(app=app)
    image_urls = []
    
    for blob in bucket_1.list_blobs():
        name = str(blob.name)
        #print(name)
        blob_img = bucket_1.blob(name)
        X_url = blob_img.generate_signed_url(datetime.timedelta(seconds = 300), method='GET')
        #print(X_url)
        image_urls.append(X_url)
    
    
    PATH = ['Where you want to save the image']
    for path in PATH:
        i = 1
        for url  in image_urls:
            name_img = str(path + "image"+str(i)+".jpg")
            image_download(url, name_img)
            i+=1
    
    0 讨论(0)
  • 2020-11-21 12:05

    For Android the best pratice is to use FirebaseUI and Glide.

    You need to add that on your gradle/app in order to get the library. Note that it already has Glide on it!

    implementation 'com.firebaseui:firebase-ui-storage:4.1.0'
    

    And then in your code use

    // Reference to an image file in Cloud Storage
    StorageReference storageReference = FirebaseStorage.getInstance().getReference();
    
    // ImageView in your Activity
    ImageView imageView = findViewById(R.id.imageView);
    
    // Download directly from StorageReference using Glide
    // (See MyAppGlideModule for Loader registration)
    GlideApp.with(this /* context */)
            .load(storageReference)
            .into(imageView);
    
    0 讨论(0)
  • 2020-11-21 12:12

    So I had a project that required downloading assets from firebase storage, so I had to solve this problem myself. Here is How :

    1- First, make a model data for example class Choice{}, In that class defines a String variable called image Name so it will be like that

    class Choice {
        .....
        String imageName;
    }
    

    2- from a database/firebase database, go and hardcode the image names to the objects, so if you have image name called Apple.png, create the object to be

    Choice myChoice = new Choice(...,....,"Apple.png");
    

    3- Now, get the link for the assets in your firebase storage which will be something like that

    gs://your-project-name.appspot.com/
    

    like this one

    4- finally, initialize your firebase storage reference and start getting the files by a loop like that

    storageRef = storage.getReferenceFromUrl(firebaseRefURL).child(imagePath);
    
    File localFile = File.createTempFile("images", "png");
    storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
    
    @Override
    public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
        //Dismiss Progress Dialog\\
    }
    

    5- that's it

    0 讨论(0)
  • 2020-11-21 12:15

    A workaround can be to create a file (i.e list.txt) with nothing inside, in this file you can set the custom metadata (that is a Map< String, String>) with the list of all the file's URL.
    So if you need to downlaod all the files in a fodler you first download the metadata of the list.txt file, then you iterate through the custom data and download all the files with the URLs in the Map.

    0 讨论(0)
提交回复
热议问题