Copy a file on firebase storage?

给你一囗甜甜゛ 提交于 2020-11-25 02:14:09

问题


Is it possible to copy an existing file on firebase storage without needing to uploading it again?

I need it for a published/working version setup of my app.


回答1:


There is no method in the Firebase Storage API to make a copy of a file that you've already uploaded.

But Firebase Storage is built on top of Google Cloud Storage, which means that you can use the latter's API too. It looks like gsutil cp is what you're looking for. From the docs:

The gsutil cp command allows you to copy data between your local file system and the cloud, copy data within the cloud, and copy data between cloud storage providers.

Keep in mind that gsutil has full access to your storage bucket. So it is meant to be run on devices you fully trust (such as a server or your own development machine).




回答2:


Here is an approach I ended up with for my project.

While it covers a broader case and copies all files under folder fromFolder to toFolder, it can be easily adopted to the case from the question (to copy only files one can pass delimiter = "/" - refer to the docs for more details)

const {Storage} = require('@google-cloud/storage');


module.exports = class StorageManager{

    constructor() {
        this.storage = new Storage();
        this.bucket = this.storage.bucket(<bucket-name-here>)
    }

    listFiles(prefix, delimiter){
        return this.bucket.getFiles({prefix, delimiter});
    }
    deleteFiles(prefix, delimiter){
        return this.bucket.deleteFiles({prefix, delimiter, force: true});
    }

    copyFilesInFolder(fromFolder, toFolder){
        return this.listFiles(fromFolder)
            .then(([files]) => {
                let promiseArray = files.map(file => {
                    let fileName = file.name
                    let destination = fileName.replace(fromFolder, toFolder)
                    console.log("fileName = ", fileName, ", destination = ", destination)
                    return file.copy(destination)
                })
                return Promise.all(promiseArray)
            })
    }
}


来源:https://stackoverflow.com/questions/39546037/copy-a-file-on-firebase-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!