Storing Image Using Cloud Functions for Firebase

北慕城南 提交于 2019-12-23 18:10:20

问题


I'm trying to refactor some code to use Cloud Functions for Firebase. The code should store an image at a path in Firebase storage. 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

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. 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. 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();
});

回答1:


Are you deploying your Function on Firebase with Spark Plan (Free)?

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. Requests to third-party APIs fail with an error. For more information about upgrading your project.

Since you are trying to make an external request, nothing is happening when your Function is executed :(




回答2:


Thats easy right now! Since you have admin. just change

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

to

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


来源:https://stackoverflow.com/questions/43698405/storing-image-using-cloud-functions-for-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!