将base64编码的jpeg上传到Firebase存储(Admin SDK)

Man*_*UEZ 17 node.js google-cloud-storage google-cloud-platform firebase-storage

我正在尝试从我的移动混合应用程序(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));
    });
  })
};
Run Code Online (Sandbox Code Playgroud)

我有两个主要问题:

  1. 上传成功,但是当我访问Firebase存储控制台时,当我尝试显示图片的预览时出现错误,我下载时无法从计算机中打开它.我想这是编码的事情......?
  2. 如何检索新上传的文件下载URL?我期待一个对象在被退回.on('finish),像upload()功能,但没有返回(文件是不确定的).我如何检索此网址以将其发送回服务器响应中?

我想避免使用该upload()功能,因为我不想在后端托管文件,因为它不是专用服务器.

Man*_*UEZ 10

我的问题是我data:image/jpeg;base64,在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);
      });
Run Code Online (Sandbox Code Playgroud)