繁体   English   中英

使用Firebase Cloud功能检查存储中是否存在映像

[英]Check if image exists at storage with firebase cloud function

我需要一个我创建的功能来处理用户发送到我的应用程序的图像,这需要您的帮助。

我需要的是获取用户发送的图像,调整大小并检查图像是否已更改以避免该功能再次执行。 我看到的示例更改了图像名称,并检查了该名称是否与设置的名称相等,但是在我的情况下,我需要保留图片的原始名称,那么,该怎么办? 还是存在解决此问题的更好方法? 我的功能代码是:

  import * as functions from 'firebase-functions';

  import * as Storage from '@google-cloud/storage';
  const gcs = new Storage();

  import { tmpdir } from 'os';
  import { join, dirname } from 'path';

  import * as sharp from 'sharp';
  import * as fs from 'fs-extra';

  export const generateThumbs = functions.storage
  .object()
  .onFinalize(async object => {
    const bucket = gcs.bucket(object.bucket);
    const filePath = object.name;
    const fileName = filePath.split('/').pop();
    const bucketDir = dirname(filePath);

    const workingDir = join(tmpdir(), 'thumbs');
    const tmpFilePath = join(workingDir, 'source.png');

    if (!object.contentType.includes('image')) {
      console.log('exiting function');
      return false;
    }

    // 1. Ensure thumbnail dir exists
    await fs.ensureDir(workingDir);

    // 2. Download Source File
    await bucket.file(filePath).download({
      destination: tmpFilePath
    });

    // 3. Resize the images and define an array of upload promises
    const sizes = [64, 128, 256];

    const uploadPromises = sizes.map(async size => {
      const thumbName = `thumb@${size}_${fileName}`;
      const thumbPath = join(workingDir, thumbName);

      // Resize source image
      await sharp(tmpFilePath)
        .resize(size, size)
        .toFile(thumbPath);

      // Upload to GCS
      return bucket.upload(thumbPath, {
        destination: join(bucketDir, thumbName)
      });
    });

    // 4. Run the upload operations
    await Promise.all(uploadPromises);

    // 5. Cleanup remove the tmp/thumbs from the filesystem
    return fs.remove(workingDir);
  });

如果您需要覆盖原始文件,并且希望避免使用此功能造成无限循环,则可以在将文件上传回Cloud Storage时将自定义元数据附加到文件。 然后,当对该文件再次调用该函数时,可以检查传入的ObjectMetadata对象上的元数据,以了解何时应退出该函数,而无需进行任何其他更改。

暂无
暂无

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

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