使用 Firebase 存储上传 base64 图像 [英] Upload a base64 image with Firebase Storage

查看:22
本文介绍了使用 Firebase 存储上传 base64 图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作这个应用程序,用户可以在其中拥有个人资料图片(但每个人只能拥有一张图片).我把所有东西都设置好了,但是当图片超过 2mb 时,加载需要一些时间,实际上我只需要图片大小为 50kb 左右(只显示小图片,最大 40 像素).我编写了一些代码将图像直接放入实时数据库(转换为画布并使它们成为 7kb base64 字符串).但是,这并不是很干净,最好使用 Firebase Storage.

I'm making this app where users can have a profile picture (but only one picture each). I got everything set up, but when the pictures are 2mb+, it takes some time to load and actually I just need the pictures to be 50kb or so (only small display of pictures, max 40 pixels). I made some code to put the images directly into the realtime database (convert to canvas and make them a 7kb base64 string). However, this is not really clean and it's better to use Firebase Storage.

从新的更新 3.3.0 开始,您可以使用 putString() 方法将 Base64 格式的字符串上传到 Storage.但是,当我上传画布图像(以data:image/jpeg;base64,"开头)时,出现错误:

Since the new update 3.3.0 you can upload Base64 formatted strings to Storage, using the putString() method. However, when I upload my canvas image (which starts with "data:image/jpeg;base64,"), I get the error:

v {code: "storage/invalid-format", message: "Firebase Storage: String does not match format 'base64': Invalid character found", serverResponse: null, name: "FirebaseError"}.

这个错误是不是因为一开始画布图片的字符串导致的?我已经搜索了整个堆栈,但似乎找不到答案.

Does this error occur because of string of the canvas image in the beginning? I've searched all over Stack, but I can't seem to find the answer.

推荐答案

天哪,我已经忙了很长时间了,但是在我发布这个之后,我自己找到了答案.解决方案是获取 base64 变量并删除前 23 位数字(例如:data:image/jpeg;base64,")并将其上传到 Firebase 存储.现在它被接受了,您可以通过以下方式将该链接放入您的实时数据库中:

Jeez, I've been busy for a very long time now, but just after I posted this, I've found the answer myself. The solution was to get the base64 variable and remove the first 23 digits (so: "data:image/jpeg;base64,") and upload it to the Firebase Storage. Now it gets accepted and you can put the link in your Realtime Database via:

var storageRef = firebase.storage().ref().child("Whatever your path is in Firebase Storage");
var imageRef = "Your path in the Realtime Database";

    storageRef.getDownloadURL().then(function(url) {
        imageRef.child("image").set(url);
    }); 

    var task = storageRef.putString("Your base64 string substring variable", 'base64').then(function(snapshot) {
         console.log('Uploaded a base64 string!');
         });

这篇关于使用 Firebase 存储上传 base64 图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆