使用云端功能存储图片的Firebase [英] Storing Image Using Cloud Functions for Firebase

查看:389
本文介绍了使用云端功能存储图片的Firebase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图重构一些代码来使用Firebase的云端函数。代码应该将图片存储在Firebase存储中的路径中。大部分代码与以前完全一样,除了现在,而不是

  server.post('/',(req ,res)=> {
//某些代码
}

I根据Firebase文档使用以下内容:
$ b $ pre $ export $ c $ exports.getProcessedImage = functions.https.onRequest((req,res)= > {
//一些代码
});

以前但是现在我在将测试映像保存到Firebase时遇到问题不知道为什么我在开发人员工具中检查Network选项卡,并且getProcessedImage端点正在触发代码运行,并以200代码响应,所以不知道是什么

我的完整代码如下:)

 lang-js prettyprint-override>  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项目ID和服务帐户密钥。
const gcs = storage({
projectId:'snapshelf-aabb55',
keyFilename:'./serviceAccountKey.json'
});

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

函数saveImage(url){

//使用crypto(本地节点模块)生成一个随机HEX字符串。
const randomFileName = crypto.randomBytes(16).toString('hex');

//使用HTTP HEAD请求获取图像信息。
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD
request.head(url,(error,info)=> {
if(error){
return console.error(error);
}

//从Pixelz下载图片,然后将图片保存到Firebase
/ /使用Google Cloud API和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)=> {

//如果上传失败, .error(err);
})
.on('finish',()=> {

//当一切都完成时做一些事情。

//获取存储映像的下载网址
console.log('映像成功上传到Firebase存储!')
});
});


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

//从Pixelz获取图片并保存到Firebase存储
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();
});


解决方案

免费)?

如果答案是肯定的,你的问题就是因为这个原因:


Spark计划上的Firebase项目只能对Google API发出出站请求。对第三方API的请求失败并出现错误。有关升级项目的更多信息。


由于您正在尝试创建外部请求当你的函数执行时发生:($ / b $ b

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

解决方案

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 :(

这篇关于使用云端功能存储图片的Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆