使用Firebase 3上传Base64图像

时间:2016-06-02 08:29:02

标签: javascript angularjs firebase firebase-storage

可以将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"}

3 个答案:

答案 0 :(得分:3)

您只需使用 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()和/或将src作为<img>标记。

答案 1 :(得分:1)

您可以将base64传递给返回blob的函数,例如:

{{1}}

答案 2 :(得分:0)

Firebase存储采用JS FileBlob类型,而不是字符串。您可以将base64编码数据存储在一个文件中然后上传,但我建议将它们转换为“真实”文件(onCreate()jpg判断它看起来像照片)所以你可以拥有一种内容类型,让浏览器对其进行处理,获得压缩等好处。