Firebase存储 - 有没有办法在不重命名文件的情况下使用云功能调整原始图像的大小,而不会在触发器

时间:2018-03-31 11:29:03

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

我使用firebase存储触发器分析了缩略图创建代码。

我需要调整当前图像的大小而不重命名文件,它不应该导致无限循环。

基本上,每当我将图像上传到firebase存储时,都应将其调整为特定大小,但不应更改其他属性,如下载URL,名称。

以下是生成缩略图的代码。但是,我需要让它来调整当前图像的大小。请帮忙。

这里,如果文件名是thumb_,那么只有无限循环才会停止,我需要使用其他属性来停止它,比如元数据或任何东西

exports.generateThumbnail = functions.storage.object().onChange((event) => {
  const object = event.data; 

  const fileBucket = object.bucket; 
  const filePath = object.name; 
  const contentType = object.contentType; 
  const resourceState = object.resourceState; 
  const metageneration = object.metageneration; 

  if (!contentType.startsWith('image/')) {
    console.log('This is not an image.');
    return null;
  }

  const fileName = path.basename(filePath);
  if (fileName.startsWith('thumb_')) {
    console.log('Already a Thumbnail.');
    return null;
    //Here, if the filename is having thumb_, then only the infinite loop will stop, I need to stop it using other properties like meta data or anything else
  }

  if (resourceState === 'not_exists') {
    console.log('This is a deletion event.');
    return null;
  }

  if (resourceState === 'exists' && metageneration > 1) {
    console.log('This is a metadata change event.');
    return null;
  }

  const bucket = gcs.bucket(fileBucket);
  const tempFilePath = path.join(os.tmpdir(), fileName);
  const metadata = {
    contentType: contentType,
  };
  return bucket.file(filePath).download({
    destination: tempFilePath,
  }).then(() => {
    console.log('Image downloaded locally to', tempFilePath);
    return spawn('convert', [tempFilePath, '-thumbnail', '200x200>', tempFilePath]);
  }).then(() => {
    console.log('Thumbnail created at', tempFilePath);
    const thumbFileName = `thumb_${fileName}`;
    const thumbFilePath = path.join(path.dirname(filePath), thumbFileName);
    return bucket.upload(tempFilePath, {
      destination: thumbFilePath,
      metadata: metadata,
    });
  }).then(() => fs.unlinkSync(tempFilePath));
});

1 个答案:

答案 0 :(得分:0)

将自定义元数据传递到上传功能:

return bucket.upload(tempFilePath, {
  destination: filePath,
  metadata: {
    contentType,
    metadata: {
      isThumb: 'true',
    }
  },
})

替换文件时,将再次触发云功能。要打破循环,请检查自定义元数据:

/**
  * File metadata.
  */
const meta = object.metadata;

/**
  * Exit if the image is already a thumbnail.
  */
if (meta && meta.isThumb == 'true') {
   console.log('Already a Thumbnail.');
   return null;
}