【问题标题】:How to store Firebase URL in variable on File upload如何在文件上传时将 Firebase URL 存储在变量中
【发布时间】:2020-06-25 19:15:28
【问题描述】:

我正在尝试使用 firebase 存储和 firestore 在 react-js 中创建上传功能。我有一个功能可以将文件上传到firebase存储,然后将一些数据发布到firestore。我希望文件的 url 与去 firestore 的数据一起使用。到目前为止,我只能将 URL 记录到控制台,但我无法存储它。我在网上和 firebase 文档中查看了所有内容,但找不到在上传时存储 URL 的方法。

如果您对我可以尝试的事情有任何建议,我将不胜感激:)

publishHandler = (event) => {
    event.preventDefault();
    console.log(this.state.input);
    let url = "";
    let file = this.state.input.image;
    let storageRef = firebase.storage().ref();
    let uploadTask = storageRef.child("uploads/" +file.name).put(file);
    uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, 
        function (snapshot) {
            let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log("upload is " + progress + " % done.");
        },
        function(error) {
            console.log("Something went wrong..." + error);
        },
        function(complete) {
            uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {
                console.log(downloadURL);
                // Here is where I wish I could store the downloadURL into the url variable declared earlier
                url = downloadURL;

            });
        }
        );

    // Post data to firebase.
    db.collection("hittat").doc().set({
        title: this.state.input.title,
        amount: this.state.input.amount,
        description: this.state.input.description,
        url: url;
    });

};

【问题讨论】:

  • 为什么不能存储 URL?看起来您想要存储 URL 的代码点就是您实际想要放置编写文档的现有代码的位置。
  • 感谢道格的回复!因此,此代码失败,因为无法在函数内部设置变量 url。我想这与范围有关?
  • 这与 Firebase API 都是异步的这一事实有关。

标签: javascript firebase google-cloud-firestore firebase-storage


【解决方案1】:

我想看看能不能找到一个重复的,但我想给你你需要先使用的代码。

正如 Doug 所说,任何需要访问下载 URL 的代码都需要在 getDownloadURL().then 回调中。

所以在你的情况下:

uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, 
    function (snapshot) {
        let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        console.log("upload is " + progress + " % done.");
    },
    function(error) {
        console.log("Something went wrong..." + error);
    },
    function(complete) {
        uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {
            console.log(downloadURL);
            // Here is where I wish I could store the downloadURL into the url variable declared earlier
            url = downloadURL;

            db.collection("hittat").doc().set({
                title: this.state.input.title,
                amount: this.state.input.amount,
                description: this.state.input.description,
                url: url;
            });
        });
    });

这可能也意味着您不再需要 url 变量。

另见:

【讨论】:

  • 非常感谢弗兰克!我会试一试。像这样在函数内部这样做是有意义的。
猜你喜欢
  • 2020-07-05
  • 2020-04-08
  • 1970-01-01
  • 2020-09-27
  • 1970-01-01
  • 2019-03-26
  • 2020-07-27
  • 2021-08-12
  • 1970-01-01
相关资源
最近更新 更多