使用 Firebase 3 上传 Base64 图片

Upload Base64 image with Firebase 3

可以将 base64 图像上传到 Firebase 吗?

我试过这段代码:

                    var storageRef = firebase.storage().ref();
                console.log(storageRef);                                        
                var file = "data:image/jpeg;base64,BASE64.....";

                var uploadTask = storageRef.child('avatars/'+user.providerData[0].uid+'/photo-'+$scope.number+'.jpg').put(file);
                uploadTask.on('state_changed', function(snapshot){
                }, function(error) {
                  console.log('error');
                }, function() {
                  console.log('success');
                  var downloadURL = uploadTask.snapshot.downloadURL;
                });

但是我有一个错误:

{code: "storage/invalid-argument", message: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.", serverResponse: null, name: "FirebaseError"}

Firebase 存储采用 JS File or Blob 类型,而不是字符串。您可以将 base64 编码数据存储在一个文件中,然后上传它,尽管我建议将它们转换为 "real" 文件(jpgpng 判断它看起来像一张照片)这样您可以有一个内容类型,让浏览器这样对待它,获得压缩等好处。

您可以将 base64 传递给函数,该函数 returns 像这样的 blob:

base64toBlob(base64Data, contentType) {
        contentType = contentType || '';
        var sliceSize = 1024;
        var byteCharacters = atob(base64Data);
        var bytesLength = byteCharacters.length;
        var slicesCount = Math.ceil(bytesLength / sliceSize);
        var byteArrays = new Array(slicesCount);

        for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
            var begin = sliceIndex * sliceSize;
            var end = Math.min(begin + sliceSize, bytesLength);

            var bytes = new Array(end - begin);
            for (var offset = begin, i = 0 ; offset < end; ++i, ++offset) {
                bytes[i] = byteCharacters[offset].charCodeAt(0);
            }
            byteArrays[sliceIndex] = new Uint8Array(bytes);
        }
        return new Blob(byteArrays, { type: contentType });
    }

只需要使用putString函数,无需将BASE64转为blob

firebase.storage().ref('/your/path/here').child('file_name')
.putString(your_base64_image, ‘base64’, {contentType:’image/jpg’});

确保将元数据 {contentType:'image/jpg'} 作为 第三个参数(可选)到函数 putString,以便您以图像格式检索数据。

或者简单地说:

uploadTask = firebase.storage().ref('/your/path/here').child('file_name').putString(image, 'base64', {contentType:'image/jpg'});
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) {
    console.log(error);
}, function() {
  // Upload completed successfully, now we can get the download URL
  var downloadURL = uploadTask.snapshot.downloadURL;
});

然后您可以使用 downloadURL 保存到 firebase.database() and/or 以作为 src 放入 <img> 标签。