首页 > 解决方案 > 将 jpg 上传到 Firebase 存储不会完全上传文件

问题描述

我正在尝试编写一个函数,将 jpeg 图像上传到 firebase 存储并返回上传文件的下载链接。但是当我执行该函数时,文件并没有完全上传到存储中,即原始文件大小为 10 KB,上传文件大小为 9 B。我正在使用以下代码:

    const storageRef = firebase.storage().ref();
    const dpRef = storageRef.child("users/dp.jpg").put(file, {
      contentType: "image/jpeg",
    });

    dpRef.on(
      firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
      (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");
            console.log(progress);
            break;
          default:
            break;
        }
      },
      (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
            console.log("Unauthorized");
            break;
          case "storage/canceled":
            // User canceled the upload
            console.log("Cancelled");
            break;

          // ...

          case "storage/unknown":
            // Unknown error occurred, inspect error.serverResponse
            console.log("Unknown");
            break;
          default:
            break;
        }
      },
      () => {
        // Upload completed successfully, now we can get the download URL
        dpRef.snapshot.ref.getDownloadURL().then((downloadURL) => {
          console.log("File available at", downloadURL);
        });
      }
    );

console.log(progress)出于某种原因,显示 NaN 。我也试过下载

标签: javascriptgoogle-cloud-storagefirebase-storage

解决方案


我不确定是什么问题,但我最近这样做了,我可以分享我的代码:

import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/storage';

const uploadImageFetch = async (uri) => {
    const blob = await new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.onload = function () {
            resolve(xhr.response);
        };
        xhr.onerror = function (e) {
            console.log(e);
            reject(new TypeError('Network request failed'));
        };
        xhr.responseType = 'blob';
        xhr.open('GET', uri, true);
        xhr.send(null);
    });
    const imageNameBefore = uri.split('/');
    const imageName = imageNameBefore[imageNameBefore.length - 1];

    const ref = firebase.storage().ref().child(`images/${imageName}`);
    const snapshot = await ref.put(blob);
    blob.close();
    return await snapshot.ref.getDownloadURL();
};

此函数接受带有图像的本地 URI,并返回下载 URL。您可以在官方文档https://firebase.google.com/docs/storage/web/upload-files中查看更多示例


推荐阅读