将base64编码的jpeg上传到Firebase存储(Admin SDK)
问题描述:
我试图从我的移动混合应用程序(Ionic 3)将图片发送到我的Heroku后端(Node.js),并让后端将图片上传到Firebase存储,将新上传的fil下载网址返回到移动应用程序。将base64编码的jpeg上传到Firebase存储(Admin SDK)
请记住,我正在为Node.js使用Firebase Admin SDK。
所以我送编码图像的Heroku以base64(我有一个在线的base64解码器检查编码字符串,它是正常的),这是由下面的函数处理:
const uploadPicture = function(base64, postId, uid) {
return new Promise((resolve, reject) => {
if (!base64 || !postId) {
reject("news.provider#uploadPicture - Could not upload picture because at least one param is missing.");
}
let bufferStream = new stream.PassThrough();
bufferStream.end(new Buffer.from(base64, 'base64'));
// Retrieve default storage bucket
let bucket = firebase.storage().bucket();
// Create a reference to the new image file
let file = bucket.file(`/news/${uid}_${postId}.jpg`);
bufferStream.pipe(file.createWriteStream({
metadata: {
contentType: 'image/jpeg'
}
}))
.on('error', error => {
reject(`news.provider#uploadPicture - Error while uploading picture ${JSON.stringify(error)}`);
})
.on('finish', (file) => {
// The file upload is complete.
console.log("news.provider#uploadPicture - Image successfully uploaded: ", JSON.stringify(file));
});
})
};
我有2个主要问题:
- 上传成功,但我当我去火力地堡存储控制台,还有当我尝试显示图片的预览,当我下载它,我无法从我的电脑打开它是一个错误。我想这是一个编码的东西....?
- 如何检索新上传的文件下载网址?我期待在
.on('finish)
中返回一个对象,如upload()
函数,但没有返回(文件未定义)。我怎么能检索这个网址发回服务器响应?
我想避免使用upload()
函数,因为我不想在后端托管文件,因为它不是专用服务器。
答
我的问题是,我在base64对象字符串的开头添加了data:image/jpeg;base64,
;我只是要删除它。
对于下载网址,我做了以下内容:
const config = {
action: 'read',
expires: '03-01-2500'
};
let downloadUrl = file.getSignedUrl(config, (error, url) => {
if (error) {
reject(error);
}
console.log('download url ', url);
resolve(url);
});
我是这么久,是因为“上载”方法不起作用寻找答案。我的朋友,你很棒!奇迹般有效!非常感谢你分享代码和你的结果! –