如何使用firebase存储移动文件?

时间:2016-07-26 23:41:51

标签: firebase firebase-storage

有没有办法用firebase.storage()移动文件?

实施例: user1 / public / image.jpg到user1 / private / image.jpg

3 个答案:

答案 0 :(得分:8)

由于Firebase存储由Google云端存储支持,因此您可以使用GCS的rewrite API(docs)或gsutil mvdocs)。

此外,GCloud Node中的movedocs)示例如下:

var bucket = gcs.bucket('my-bucket');
var file = bucket.file('my-image.png');
var newLocation = 'gs://another-bucket/my-image-new.png';
file.move(newLocation, function(err, destinationFile, apiResponse) {
  // `my-bucket` no longer contains:
  // - "my-image.png"
  //
  // `another-bucket` now contains:
  // - "my-image-new.png"

  // `destinationFile` is an instance of a File object that refers to your
  // new file.
});

答案 1 :(得分:6)

没有这种方法可以移动到其他位置,而是可以下载然后将其放到其他参考位置并删除以前的位置。

答案 2 :(得分:1)

我编写了一个JavaScript函数,该函数仅使用firebase存储API来完成此操作。

快乐编码!

/**
 * Moves a file in firebase storage from its current location to the destination
 * returns the status object for the moved file.
 * @param {String} currentPath The path to the existing file from storage root
 * @param {String} destinationPath The desired pathe for the existing file after storage
 */
function moveFirebaseFile(currentPath, destinationPath) {
    let oldRef = storage.ref().child(currentPath)

    oldRef.getDownloadURL().then(url => {
        fetch(url).then(htmlReturn => {
            let fileArray = new Uint8Array()
            const reader = htmlReturn.body.getReader()

            //get the reader that reads the readable stream of data
            reader
                .read()
                .then(function appendStreamChunk({ done, value }) {
                    //If the reader doesn't return "done = true" append the chunk that was returned to us
                    // rinse and repeat until it is done.
                    if (value) {
                        fileArray = mergeTypedArrays(fileArray, value)
                    }
                    if (done) {
                        console.log(fileArray)
                        return fileArray
                    } else {
                        // "Readout not complete, reading next chunk"
                        return reader.read().then(appendStreamChunk)
                    }
                })
                .then(file => {
                    //Write the file to the new storage place
                    let status = storage
                        .ref()
                        .child(destinationPath)
                        .put(file)
                    //Remove the old reference
                    oldRef.delete()

                    return status
                })
        })
    })
}