最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Firebase image upload in async await manner - Stack Overflow

programmeradmin1浏览0评论

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 pletion 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
            // 
            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 pleted 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!");
      }
    }

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 pletion 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./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 pleted 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 pleted 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?

Share edited Aug 23, 2023 at 10:28 Renaud Tarnec 83.2k10 gold badges98 silver badges129 bronze badges Recognized by Google Cloud Collective asked Apr 23, 2019 at 7:12 margherita pizzamargherita pizza 7,18529 gold badges102 silver badges178 bronze badges 2
  • what's your question here? do you want to use async/await? – Jack Commented Apr 23, 2019 at 7:19
  • @jackz314 Yes! I have mark the correct answer also. – margherita pizza Commented Apr 23, 2019 at 8:03
Add a ment  | 

2 Answers 2

Reset to default 8

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

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

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!");
      }
    }

In case anyone needs to both observe upload progress while using await/async instead of callbacks, this code works:

try {
   await saveToFirebase();
   alert("Happy days!");
} catch (error) {
   alert("Sad days!");
}


async function saveToFirebase() {
   // Create promise.
   let promise = $.Deferred();

   // Set storage reference.
   let storageRef = firebase.storage().ref();

   // Se file path.
   let filepath = "your-path.txt";

   // Set content type.
   let metadata = {
      contentType: "text/plain",
      cacheControl: "no-cache, max-age=0"
   };

   // Start upload.
   let uploadTask = storageRef.child(filepath).putString(data, "raw", metadata);

   // Monitor state of upload operation.
   uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, function(snapshot) {
      // Get task progress, including number of bytes uploaded and total number of bytes to be uploaded.
      let progress = (snapshot.bytesTransferred / snapshot.totalBytes);
      
      // Display progress to user.

   // Error during upload?
   }, function(error) {
      promise.reject(error);

   // Nope, upload succeeded.
   }, function() {
      promise.resolve();
   });

   // Return promise.
   return promise;
}
发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>