无法使用Firebase函数将字节数组图像上传到火存储

时间:2019-02-15 11:06:58

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

我无法使用云功能将字节数组格式的图像文件上传到Firestore。下面的代码在本地使用 app.listen()可以正常工作,但是当我尝试使用 exports 功能时

...
services:
  prisma:
    entrypoint: ["/bin/sh", "-c", "'./wait-for-it.sh db:3306 && /app/start.sh'"] 

有人可以帮我吗。预先感谢

3 个答案:

答案 0 :(得分:1)

这是我使用 Firebase功能 Google Cloud Pub / Sub 将文件上传到 Firebase存储时的最终解决方案。

  

注意发布/订阅是可选的,仅适用于我的用例

const functions = require('firebase-functions');
const admin = require('firebase-admin');

function saveImage(filename, data) {
    const bucket = admin.storage().bucket();
    const imageBuffer = new Uint8Array(data);
    const file = bucket.file(`optional_sub_directory/${filename}`, {
        uploadType: {resumable: false}
    });

    file.save(imageBuffer, (err) => {
        if (err) {
            console.error(`Error uploading: ${filename} with message: ${err.message}`);
            return;
        }

        console.log('Uploaded file');
    });
}

exports.helloPubSub = functions.pubsub
    .topic('demo-topic')
    .onPublish(async(message) => {
        /**
         *  Here goes code to extract the file buffer
         */

        const buffer = /** buffer */

        saveImage("stack_overflow.txt", buffer);
    });

答案 1 :(得分:0)

经过一番阅读后,将图像上传到Firebase存储中。我意识到,除了将字节数组转换为Image之外,我们还可以直接使用 Uint8Array()上传字节数组,该数组会自动将其转换为Image并上传到Firebase存储中。下面是修改后的代码。

const functions = require('firebase-functions');
const { Storage } = require('@google-cloud/storage');
const express = require('express');
var app = express();

// Your Google Cloud Platform project ID
const projectId ='<project-Id>';

// Creates a client
const storage = new Storage({

    projectId: projectId,
    keyFilename: './servicekey.json'
});


const bucket = storage.bucket("<bucket-name>");

const options = {
    action: 'read',
    expires: '03-17-2025'
};

// storing Byte array

function saveImage(filename, data) {

 var imageBuffer = new Uint8Array(data);
 var file = bucket.file(filename);

 file.save(imageBuffer, {
           metadata: { contentType: 'image/png' },
           }, 
           ((error) => {

           if (error) {
              console.log('error')
           }
        file.getSignedUrl(options)
        .then(results => {
            const url = results[0];
            console.log(`The signed url for ${imageName} is ${url}.`);
        })
 }));

}

saveImage("image1.png", <byte-Array as input>);


app.use(function (req, res, next) {
 res.header("Access-Control-Allow-Origin", "*");
 res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, 
 Content-Type, Accept");
 next();
});



exports.UploadImage = functions.https.onRequest(app);

答案 2 :(得分:0)

感谢您的回复。我使用了相同的方法,但是有两个问题。第一个是在运行函数时我没有得到响应,尽管正在上传图像。另外一个问题是下载后以及 Firebase 页面上都看不到图像。我已将 ContentType 设置为'image / jpg'
enter image description here

这是我的代码:

const bucket = admin.storage().bucket();

  try {
    const imageBuffer = new Uint8Array(req.rawBody);
    const file = bucket.file(`projects/sample.jpg`);

    file.save(
      imageBuffer,
      { resumable: false, metadata: { contentType: "image/jpg" } },
      err => {
        if (err) {
          throw new Error(err);
        }
        res.send({
          success: true,
          message: "File Successfully Uploaded..."
        });
      }
    );

  } catch (error) {
    throw new Error(error);
  }