Seb*_*ist 6 javascript firebase firebase-storage
使用firebase 3.0.x,是否可以将base64编码的映像保存到新的Firebase存储服务?
我在上传之前使用canvas在浏览器中调整图像大小,并将它们输出为base64 jpeg.我知道Storage api可以接受Blob,但我目前的项目需要IE9支持.
Niñ*_*ura 11
您只需要使用putString函数而不将BASE64转换为blob.
firebase.storage().ref('/your/path/here').child('file_name')
.putString(your_base64_image, ‘base64’, {contentType:’image/jpg’});
Run Code Online (Sandbox Code Playgroud)
确保将元数据{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;
});
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用downloadURL保存到firebase.database()和/或将src作为<img>标记放置.
Firebase SDK 的最新版本支持 base64 图片上传。只需使用putStringFirebase Storage 中的方法即可。
https://firebase.google.com/docs/reference/js/firebase.storage
一个小小的警告是,有时您会得到一个带有不必要空格的 base64 字符串。例如,我发现cordova Camera 插件返回base64 并带有不必要的空格。Storage SDK 将无法上传此内容,因为 JavaScript 无法执行其本机atob功能 - Firebase JS 在幕后执行的操作。您必须去除空格 - 请参阅JavaScript 中有效 base64 图像字符串上的 DOM Exception 5 INVALID CHARACTER 错误
是的,现在可以了。您应该使用名为putString. 你可以在这里阅读规范。
所以,Firebase 规范说你现在有两种方法来存储 Base64 字符串和 Base64url 字符串:
// Base64 formatted string
var message = '5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB';
ref.putString(message, 'base64').then(function(snapshot) {
console.log('Uploaded a base64 string!');
});
// Base64url formatted string
var message = '5b6p5Y-344GX44G-44GX44Gf77yB44GK44KB44Gn44Go44GG77yB';
ref.putString(message, 'base64url').then(function(snapshot) {
console.log('Uploaded a base64url string!');
})
Run Code Online (Sandbox Code Playgroud)
根据我的经验,使用putString(message, 'base64url')不断返回 Error about bad formatted Base64 string code: "storage/invalid-format", message: "Firebase Storage: String does not match format 'base64': Invalid character found"。解决方案是切断字符串的开头 data:image/jpeg;base64,并改用第一种方法putString(message, 'base64')。然后它起作用了。
| 归档时间: |
|
| 查看次数: |
13608 次 |
| 最近记录: |