如何使用 Cloud Function with Flutter 从新图像中获取 URL?

Posted

技术标签:

【中文标题】如何使用 Cloud Function with Flutter 从新图像中获取 URL?【英文标题】:How to get a URL from a new image using Cloud Function with Flutter? 【发布时间】:2018-12-21 22:03:43 【问题描述】:

如何从具有图像名称的火存储中的新图像中获取 URL?

我正在使用 firebase_storage 插件通过 Flutter 上传图片

flutter 中的代码:

StorageReference ref =
    FirebaseStorage.instance.ref().child("$stamp.jpg");
    StorageUploadTask uploadTask = ref.putFile(imageFile);
    Uri downloadUrl = (await uploadTask.future).downloadUrl;
    downloadableUrl = downloadUrl.toString();

但是图片太大了,所以我创建了一个云函数来从这个上传的图片中生成质量较低的图片。

云功能:

const functions = require("firebase-functions");
const gcs = require('@google-cloud/storage')();
const os = require('os');
const path = require('path');
const spawn = require('child-process-promise').spawn;

exports.onFileChange= functions.storage.object().onChange(event => 
    const object = event.data;
    const bucket = object.bucket;
    const contentType = object.contentType;
    const filePath = object.name;
    console.log('File change detected, function execution started');

    if (object.resourceState === 'not_exists') 
        console.log('We deleted a file, exit...');
        return;
    

    if (path.basename(filePath).startsWith('resized-')) 
        console.log('We already renamed that file!');
        return;
    

    const destBucket = gcs.bucket(bucket);
    const tmpFilePath = path.join(os.tmpdir(), path.basename(filePath));
    const metadata =  contentType: contentType ;
    return destBucket.file(filePath).download(
        destination: tmpFilePath
    ).then(() => 
        return spawn('convert', [tmpFilePath, '-resize', '500x500', tmpFilePath]);
    ).then(() => 
        return destBucket.upload(tmpFilePath, 
            destination: 'resized-' + path.basename(filePath),
            metadata: metadata
        )
    );
);

如何在颤动中获得调整大小图像的 URL?我需要在数据注册中使用这个 URL

【问题讨论】:

【参考方案1】:

我很确定没有简单的方法。

我会在 Firebase 中维护一个表,其中原始文件名作为键,新文件名作为值。

您从上面的云函数创建条目,并使用 Firebase 数据库访问(实时数据库或 Cloud Firestore)从 Flutter 中读取它

【讨论】:

这确实是最常用的方法,使用 Firebase 实时数据库或 Cloud Firestore 作为信号机制/消息总线。我最常在数据库写入时触发 Cloud Function,然后在上传图像后从客户端代码执行此操作。 Cloud Function 读取元数据,找到文件并调整其大小,然后将响应写回预先约定的位置。现在您也可以考虑为此使用Callable HTTPS function。

以上是关于如何使用 Cloud Function with Flutter 从新图像中获取 URL?的主要内容,如果未能解决你的问题,请参考以下文章