首页 > 解决方案 > Node.js Firebase 函数将 Base64 图像发送到外部 API

问题描述

我在 Node.js 中使用带有存储触发器的 Firebase 函数将上传的图像数据发送到上传照片的外部 API 端点。

我目前正在将图像上传到我的 Firebase 存储中的存储桶中,将它们转换为 base64 字符串,然后将它们插入我的字典中以获取请求。

我目前的问题是字典似乎被缩短了。我查看了 Firebase 控制台上的控制台日志,似乎它在 base64 变量之后结束。

我不确定这是语法错误,还是我使用 base64 的方式或 Firebase 函数的错误。如果有人知道可能发生了什么,请告诉我。

const request = require('request-promise');
const gcs = require('@google-cloud/storage')();
const path = require('path');
const os = require('os');
const fs = require('fs');
const firebase = require('firebase');

exports.identifyUpdate = functions.storage.object().onFinalize((object) => {

    const fileBucket = object.bucket;
    const filePath = object.name;
    const contentType = object.contentType;
    const fileName = path.basename(filePath);

    if(!filePath.substring(0,filePath.indexOf('/')) == 'updates') {
        console.log("Triggered by non-update photo")
        return null;
    }

    console.log("Update photo added")

    // Create Firebase app (for Realtime Database access)

    var config = {
        apiKey: "[apikey]",
        authDomain: "[PROJECT_ID].firebaseapp.com",
        databaseURL: "https://[PROJECT_ID].firebaseio.com",
        storageBucket: "[PROJECT_ID].appspot.com",
    };

    if(!firebase.apps.length) {
        firebase.initializeApp(config);
    }

    // Trace back to Update stored in Realtime Database

    const database = firebase.database().ref()
    const pendingRef = database.child('pendingUpdates')

    console.log(filePath)

    const splitPath = filePath.split(path.sep)

    const patientID = splitPath[1]
    console.log('Patient ID: ' + patientID)

    const updateID = splitPath[2]
    console.log('Update ID: ' + updateID)

    const updateRef = pendingRef.child(patientID).child(updateID)

    console.log('Found Update reference')

    const photoRef = updateRef.child('photoURLs').child(fileName)

    console.log('Photo Reference: ' + photoRef)

    // Download and convert image to base64

    const bucket = gcs.bucket(fileBucket)
    const tempFilePath = path.join(os.tmpdir(), fileName)
    const metadata = {
        contentType: contentType
    };

    var base64;

    return bucket.file(filePath).download({
        destination: tempFilePath
    }).then(() => {
        console.log('Image downloaded locally to', tempFilePath)
    }).then(() => {

        base64 = base64_encode(tempFilePath)
        console.log("Base 64: " + base64)

    }).then(() => {
    // Send image data to Kairos

        var options = {
            method: 'POST',
            uri: 'https://api.kairos.com/recognize',
            body: {
                'image': base64,
                'gallery_name': 'gallerytest1'
            },
            headers: {
                'app_id': '[id]',
                'app_key': '[key]'
            },
            json: true
        }

        return new Promise (() => {
            console.log(options)
            request(options)
            .then(function(repos) {

                console.log('API call succeeded');

                console.log('Kairos response: ' + repos);

                const apiResult = repos['images']['transaction']['subject_id']
                console.log("Transaction " + JSON.stringify(apiResult))

            })
            .catch(function(err) {
                console.log('API call failed')
            })
        });

    })

    // Delete app instance (to prevent concurrency leaks)

    const deleteApp = () => app.delete().catch(() => null);
    deleteApp.call

})

function base64_encode(file) {
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer(bitmap).toString('base64');
}

图像输出: 输出

标签: node.jsfirebasebase64google-cloud-functionsfirebase-storage

解决方案


推荐阅读