【问题标题】:Storing Image Using Cloud Functions for Firebase使用 Cloud Functions for Firebase 存储图像
【发布时间】:2017-09-27 15:31:13
【问题描述】:

我正在尝试重构一些代码以使用 Cloud Functions for Firebase。该代码应将图像存储在 Firebase 存储的路径中。在大多数情况下,代码与以前完全相同,除了现在而不是

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

根据 Firebase 文档,我正在使用以下内容

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

该代码以前有效,但现在我无法将测试图像保存到 Firebase。不知道为什么。我检查了开发人员工具中的网络选项卡,getProcessedImage 端点正在触发代码运行,它以 200 代码响应,所以不确定问题是什么。提前感谢您的帮助!

我的完整代码如下:)

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

【问题讨论】:

  • 嗨@maxwellgover,谢谢你的问题!我采用了一种非常相似的方法并且确实让它发挥了作用,可能是因为我正在使用下面提到的 Blaze 计划。但是......即使图像保存在 Firebase Storage Cloud 上,具有正确的图像标题和总 Kb......不知何故,图像没有在 Firebase 控制台仪表板内打开......这几乎是文件损坏或使用错误的方法或其他东西保存。当我导航到存储桶控制台内的 img 时,图像缩略图一直显示一个微调器。任何想法这可能是什么?

标签: javascript firebase firebase-storage google-cloud-functions firebase-cloud-functions


【解决方案1】:

您是否使用 Spark 计划(免费)在 Firebase 上部署您的函数?

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

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

由于您尝试发出外部请求,因此在执行您的函数时什么都没有发生:(

【讨论】:

  • 这条规则改了吗?我在当前的定价计划中找不到它。
  • @FabioMarzocca,不,它没有改变。只需查看单击服务旁边的 ? 图标时显示的消息:它显示“Spark 计划仅允许对 Google 拥有的服务 (...) 的出站网络请求”。跨度>
【解决方案2】:

现在很容易!因为你有管理员。换个方式

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

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

【讨论】:

    猜你喜欢
    • 2018-02-28
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    相关资源
    最近更新 更多