FirebaseError: Firebase Storage: String does not match format 'base64': Invalid character found

FirebaseError: Firebase Storage: String does not match format 'base64': Invalid character found

我正在尝试将 base64 图像上传到我的 forebase 存储。我寻找了很长时间的方法,但找不到,甚至在堆栈溢出时也找不到。当我尝试上传图片时出现此错误,指出字符串不是 base64 格式。我在几个将 base64 转换为图像的网站上粘贴了相同的字符串,并且效果很好,所以字符串没问题。我不知道我错过了什么,我不知道下一步该做什么......我真的很感激任何帮助。 这是我的代码:

const storageRef = firebase.default.storage().ref().child("users")
    storageRef.putString(base64String, 'base64', { contentType: "image/jpg" }).then(snap => {
        console.log("yay");
    }).catch(err => {
        console.log("not good");
    })

我的 base64 字符串没有以“data:image/jpg;base64”开头,它看起来像这样:“/9j/4...poi//Z”

我不确定 firebase npm package was intended to be used with Node.js, I think "firebase admin" 是否比我在网上阅读的内容更好。很多人在转换 base64 和从 base64 转换时遇到问题,他们编写了自己的“atob: 和”btoa“polyfill 函数,以便这个包可以与 Node.js 一起使用。此外,这个 firebase 包需要“XMLHttpRequest”这是特定于浏览器的,但如果你愿意,你可以安装更多的 polyfills - 就像我在下面所做的那样 - 虽然看起来很难看。在浏览器中使用“firebase”npm 包可能更容易而不是 node.js .

我能让它工作的唯一方法是将 base64 字符串转换为 blob,然后上传它,如下所示:

const firebase = require("firebase/app");
require("firebase/storage");
global.XMLHttpRequest = require("xhr2"); //polyfill
let app = firebase.initializeApp({
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
});
let base64String = `iVBORw0KGgoAAAANS......`

const storageRef = firebase.storage().ref();
const imageRef = storageRef.child("123.jpeg");

//convert base64 to buffer / blob
const blob = Buffer.from(base64String, "base64");

imageRef
  .put(blob, {
    contentType: "image/jpeg",
  })
  .then(function (snapshot) {
    //console.log(snapshot);
    console.log("Uploaded blob");
  });

上传的 blob 在 firebase 存储中正确显示为图像,URL 可能在快照的元数据中。这是我用于测试的图像: https://firebasestorage.googleapis.com/v0/b/testbase64-12cae.appspot.com/o/123.jpeg?alt=media&token=23ccfe34-907f-405b-a11a-3ae686941d3f