【问题标题】:Upload base64 encoded jpeg to Firebase Storage (Admin SDK)将 base64 编码的 jpeg 上传到 Firebase 存储(Admin SDK)
【发布时间】:2017-11-25 17:55:17
【问题描述】:

我正在尝试从我的移动混合应用程序 (Ionic 3) 将图片发送到我的 Heroku 后端 (Node.js) 并让后端将图片上传到 Firebase 存储并将新上传的 fil 下载 url 返回到移动应用程序.

请记住,我正在使用适用于 Node.js 的 Firebase Admin SDK。

所以我将 base64 编码图像发送到 Heroku(我使用在线 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));
    });
  })
};

我有两个主要问题:

  1. 上传成功,但是当我进入 Firebase 存储控制台时,尝试显示图片预览时出现错误,下载时无法从计算机打开。我猜这是一个编码的东西......?
  2. 如何找回新上传的文件下载地址?我期待在.on('finish) 中返回一个对象,就像在upload() 函数中一样,但没有返回任何对象(文件未定义)。如何检索此 url 以将其发送回服务器响应?

我想避免使用upload() 函数,因为我不想在后端托管文件,因为它不是专用服务器。

【问题讨论】:

  • 我一直在寻找答案,因为“上传”方法不起作用。我的朋友,你太棒了!奇迹般有效!非常感谢您分享代码和结果!

标签: node.js google-cloud-platform google-cloud-storage firebase-storage


【解决方案1】:

我的问题是我在 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);
      });

【讨论】:

  • 这太棒了,非常感谢!我刚刚花了好几个小时试图弄清楚图片上传。
  • 感谢 Manuel 的分享,我做了一些研究来弄清楚如何使用 firebase-admin sdk 将后端的非本地图像上传到 firebase。
  • 上帝保佑你。
猜你喜欢
  • 2019-08-02
  • 2021-07-24
  • 2021-07-30
  • 2016-09-18
  • 2021-04-05
  • 2020-11-21
  • 2023-01-27
  • 2020-05-09
  • 2021-02-20
相关资源
最近更新 更多