简体   繁体   中英

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

I am trying to upload a base64 image to my forebase storage. I looked for how to do it for a long time but couldn't find it, not even here on stack over flow. When i try to upload the image i get this error saying the string is not in format base64. I pasted the same string on several websites which converts base64 to image and it worked perfectly, so the string is OK. I don't know what i am missing, i have no clue what to do next... i will really appreciate any kind of help. This is my code:

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

My base64 string does not start "data:image/jpg;base64", it's looks like this: "/9j/4...poi//Z"

I'm not sure if the firebase npm package was intended to be used with Node.js, I think "firebase admin" might be better from what I've read online. A lot of people have issues with converting to and from base64, and they write their own "atob: and "btoa" polyfill functions so that this package can be used with Node.js. Also, this firebase package requires "XMLHttpRequest" which is specific to browsers, but you can install more polyfills of it if you want - as I did below - seems ugly though. It might be easier to use the "firebase" npm package from within a browser instead of node.js.

The only way I could get this to work was by converting the base64 string to a blob and then uploading that, like so:

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

The uploaded blob displays correctly as an image in firebase storage, the URL might be in the metadata of the snapshot. Here is the image I used for testing: https://firebasestorage.googleapis.com/v0/b/testbase64-12cae.appspot.com/o/123.jpeg?alt=media&token=23ccfe34-907f-405b-a11a-3ae686941d3f

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM