1 回答

TA貢獻1817條經驗 獲得超6個贊
我不確定firebase?npm 包是否打算與 Node.js 一起使用,我認為根據我在網上閱讀的內容,“firebase admin”可能會更好。很多人在與 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 可能位于快照的元數據中。
添加回答
舉報