简体   繁体   English

使用Cloud功能为Firebase存储图像

[英]Storing Image Using Cloud Functions for Firebase

I'm trying to refactor some code to use Cloud Functions for Firebase. 我正在尝试重构一些代码以使用Cloud Functions for Firebase。 The code should store an image at a path in Firebase storage. 代码应将图像存储在Firebase存储中的路径中。 For the most part the code is the exact same as before except now instead of 在大多数情况下,代码与之前完全相同,除了现在而不是

server.post('/', (req, res) => {
  // Some code 
}

I'm using the following according to the Firebase documentation 我根据Firebase文档使用以下内容

exports.getProcessedImage = functions.https.onRequest((req, res) => {
  // Some code
});

The code worked previously but now I'm having trouble getting my test image to save to Firebase. 该代码以前工作但现在我无法将我的测试图像保存到Firebase。 Not sure why. 不知道为什么。 I check the Network tab in developer tools and the getProcessedImage endpoint is triggering the code to run and it responds with a 200 code so not sure what the issue is. 我检查开发人员工具中的“网络”选项卡,并且getProcessedImage端点正在触发要运行的代码,并且它以200代码响应,因此不确定问题是什么。 Thanks in advance for any help! 在此先感谢您的帮助!

My full code is below :) 我的完整代码如下:)

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

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const request = require('request');
const crypto = require('crypto');
const storage = require('@google-cloud/storage');

// Firebase Project ID and Service Account Key.
const gcs = storage({
  projectId: 'snapshelf-aabb55',
  keyFilename: './serviceAccountKey.json'
});

const bucket = gcs.bucket('snapshelf-aabb55.appspot.com');

function saveImage(url) {

    // Generate a random HEX string using crypto (a native node module).
    const randomFileName = crypto.randomBytes(16).toString('hex');

    // Fetch image info using a HTTP HEAD request.
    // https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD
    request.head(url, (error, info) => {
        if (error) {
            return console.error(error);
    }

    // Download image from Pixelz, then save the image to Firebase
    // using the Google Cloud API and the magic of Node Streams.
    // https://googlecloudplatform.github.io/google-cloud-node/#/docs/google-
    cloud/v0.52.0/storage/file
    // http://stackoverflow.com/questions/28355079/how-do-node-js-streams-work
    request(url)
        .pipe(
            bucket.file(`sample/images/${randomFileName}`).createWriteStream({
                metadata: {
                    contentType: info.headers['content-type']
                }
            })
        )
        .on('error', (err) => {

            // Do something if the upload fails.
            console.error(err);
        })
        .on('finish', () => {

            // Do something when everything is done.

            // Get download url for stored image
            console.log('Image successfully uploaded to Firebase Storage!')
        });
    });
}

exports.getProcessedImage = functions.https.onRequest((req, res) => {
    console.log(req.body.processedImageURL);
    /*
    if (req.body && req.body.processedImageURL) {

        // Get image from Pixelz and save it to Firebase Storage.
        saveImage(req.body.processedImageURL);

        return res.status(200).end();
    }

    res.status(400).end();
    */

    const url = 'https://www2.chemistry.msu.edu/courses/cem352/SS2017_Wulff/MichiganState.jpg'
    console.log(url);
    saveImage(url);
    console.log('Saving url');
    res.status(200).send();
});

Are you deploying your Function on Firebase with Spark Plan (Free)? 您是否使用Spark Plan(免费)在Firebase上部署功能?

If the answer is yes, your problem is because of this: 如果答案是肯定的,那你的问题是因为:

Firebase projects on the Spark plan can make only outbound requests to Google APIs. Spark计划中的Firebase项目只能向Google API发出出站请求。 Requests to third-party APIs fail with an error. 对第三方API的请求失败并显示错误。 For more information about upgrading your project. 有关升级项目的更多信息。

Since you are trying to make an external request , nothing is happening when your Function is executed :( 由于您尝试发出外部请求 ,因此执行函数时不会发生任何事情:(

Thats easy right now! 多数民众赞成在现在! Since you have admin. 既然你有管理员。 just change 只是改变

const bucket = gcs.bucket('snapshelf-aabb55.appspot.com');

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM