【问题标题】:Trigger Code When Uploading a File to Firebase Cloud Storage When Offline离线时将文件上传到 Firebase 云存储时触发代码
【发布时间】:2022-01-09 11:15:37
【问题描述】:

这是 Firebase 在其文档中用作将文件上传到 Firebase Cloud Storage 的参考的代码。

import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";

const storage = getStorage();
const storageRef = ref(storage, 'images/rivers.jpg');

const uploadTask = uploadBytesResumable(storageRef, file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', 
  (snapshot) => {
    // Observe state change events such as progress, pause, and resume
    // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
    const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    console.log('Upload is ' + progress + '% done');
    switch (snapshot.state) {
      case 'paused':
        console.log('Upload is paused');
        break;
      case 'running':
        console.log('Upload is running');
        break;
    }
  }, 
  (error) => {
    // Handle unsuccessful uploads
  }, 
  () => {
    // Handle successful uploads on complete
    // For instance, get the download URL: https://firebasestorage.googleapis.com/...
    getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
      console.log('File available at', downloadURL);
    });
  }
);

TLTR: 在uploadTask.on() 中执行只需要在离线时运行的代码的标准方法是什么(比如将文件上传到本地存储直到可以建立连接)方法?

我假设离线时,在第一个“正在运行”案例被触发后,下一个“state_changed”更新将是关于没有互联网连接并运行“暂停”案例。在这种情况下,我想编写一些代码以在离线时上传文件的情况下执行。 但是,这不会发生,并且“暂停”案例在离线或中途丢失连接时永远不会运行。错误回调也不会运行。代码只是挂在那里,直到可以建立连接。

在uploadTask.on() 方法中执行只需要在离线时运行的代码的标准方法是什么(比如将文件上传到本地存储直到可以建立连接)。

提前感谢您的帮助!

【问题讨论】:

    标签: javascript firebase google-cloud-storage progressive-web-apps offline


    【解决方案1】:

    Firebase SDK for Cloud Storage 不会将没有互联网连接视为错误情况。相反,它只会使用指数退避重试操作。

    据我所知,pause 事件仅在您自己调用 pause() 函数时触发,并且可以在 SDK source 中看到。

    【讨论】:

    • 谢谢!因此,如果我不能使用暂停,那么只有在没有连接时才在 uploadTask.on() 中运行代码的最佳方法是什么?
    • 您可以检测是否有互联网连接(与 Firebase 无关,因此在这里搜索是您的朋友),和/或检测在合理的时间后没有任何进展(许多应用程序随后使用显示“嗯..这比预期花费的时间长”消息)。
    • 好的,谢谢!我正在考虑使用 setTImeout,因为它很容易,但我认为它可能是“hacky”或不好的做法。
    • 两者都可以。如果您觉得其中一个是 hacky 或错误的,请使用另一个。 ?
    猜你喜欢
    • 2018-04-28
    • 2017-12-21
    • 2022-08-20
    • 2020-10-05
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2020-04-21
    相关资源
    最近更新 更多