Firebase图像以异步等待方式上传 [英] Firebase image upload in async await manner

查看:56
本文介绍了Firebase图像以异步等待方式上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

async UPLOAD_IMAGES() {
      try {
        let self = this;
        var storageRef = firebase.storage().ref();
        var files = document.getElementById("photoupload").files;
        var file = files[0];
        // Create the file metadata
        var metadata = {
          contentType: "image/jpeg"
        };

        // Upload file and metadata to the object 'images/mountains.jpg'
        var uploadTask = storageRef
          .child(`${this.name}/` + file.name)
          .put(file, metadata);

        // Listen for state changes, errors, and completion of the upload.
        uploadTask.on(
          firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
          function(snapshot) {
            // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
            var progress =
              (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log("Upload is " + progress + "% done");
            switch (snapshot.state) {
              case firebase.storage.TaskState.PAUSED: // or 'paused'
                console.log("Upload is paused");
                break;
              case firebase.storage.TaskState.RUNNING: // or 'running'
                console.log("Upload is running");
                break;
            }
          },
          function(error) {
            // A full list of error codes is available at
            // https://firebase.google.com/docs/storage/web/handle-errors
            switch (error.code) {
              case "storage/unauthorized":
                // User doesn't have permission to access the object
                break;

              case "storage/canceled":
                // User canceled the upload
                break;
              case "storage/unknown":
                // Unknown error occurred, inspect error.serverResponse
                break;
            }
          },
          function() {
            // Upload completed successfully, now we can get the download URL
            uploadTask.snapshot.ref
              .getDownloadURL()
              .then(function(downloadURL) {
                console.log("File available at", downloadURL);
                self = downloadURL;
              });
          }
        );
      } catch (error) {
        console.log("ERR ===", error);
        alert("Image uploading failed!");
      }
    }

这是我的上传图片的完整功能.我唯一的问题是该函数内部具有回调函数.

this is my full function for the image upload. Only issue I have is it has callback functions inside this function.

 function() {
            // Upload completed successfully, now we can get the download URL
            uploadTask.snapshot.ref
              .getDownloadURL()
              .then(function(downloadURL) {
                console.log("File available at", downloadURL);
                self = downloadURL;
              });
          } 

仅此部分可以获取异步等待功能?

Only for this part can I get async await function?

推荐答案

您可以很好地在UploadTask上调用then(),如此处所述:

You can very well call then() on an UploadTask, as explained here: https://firebase.google.com/docs/reference/js/firebase.storage.UploadTask#then

此对象的行为类似于Promise,并通过其快照进行解析 上传完成后保存数据.

This object behaves like a Promise, and resolves with its snapshot data when the upload completes.

因此您可以执行以下操作:

So you could do something like:

async UPLOAD_IMAGES() {
      try {
        let self = this;
        const storageRef = firebase.storage().ref();
        const files = document.getElementById("photoupload").files;
        const file = files[0];
        // Create the file metadata
        const metadata = {
          contentType: "image/jpeg"
        };

        const fileRef = storageRef
          .child(`${this.name}/` + file.name);

        const uploadTaskSnapshot = await fileRef.put(file, metadata);

        const downloadURL = await uploadTaskSnapshot.ref.getDownloadURL();

        self = downloadURL;

      } catch (error) {
        console.log("ERR ===", error);
        alert("Image uploading failed!");
      }
    }

这篇关于Firebase图像以异步等待方式上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆