Firebase功能-调整大小并覆盖上传到存储设备上的现有图像

Zan*_*tsu 1 javascript firebase google-cloud-functions firebase-storage

因此,我遵循了Google的官方示例,该示例创建了一个由Cloud Storage触发的Firebase函数,该函数将根据上传的图像创建调整大小的缩略图,并将它们也上传到Storage。这里简化了:

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

    // get the uploaded file data (bucket, name, type...)

    // return if the file is not an image or name begins with "thumb_"

    // download the uploaded image in a temporary local file,
    // resize it using ImageMagick
    // upload it to storage with the name "thumb_<filename>"

}
Run Code Online (Sandbox Code Playgroud)

但是,当上传新缩略图时,该功能将再次触发,依此类推。他们通过返回上传的文件是否带有“ thumb_”前缀来避免这种情况。

然后,您最终得到两张图像(原始图像和缩略图),我想用缩略图重写现有图像,所以我只有一张图像具有原始路径。

我不知道该怎么办,因为我不知道如何在不更改名称的情况下逃避重新上传循环。上传缩略图后,我可以删除原始图像,但是指向原始图像的链接已经返回并保存在实时数据库中(这些图像是用户的个人资料图片)。

Zan*_*tsu 7

在查看bucket.js@google-cloud/storagenpm模块中的文档之后,我终于设法用缩略图图像覆盖了原始文件/路径并避免了循环,

可以通过在上传缩略图时附加自定义元数据,并在下次触发该功能时测试该元数据来完成此操作。

我将发布所做的更改,其余与链接的示例相同。

测试如下:

const filePath = event.data.name
const metadata = event.data.metadata

if (metadata.isThumb) {
    console.log('Exiting: Already a thumbnail')
    return
}
Run Code Online (Sandbox Code Playgroud)

这是spawn承诺返回的部分:

    return spawn(/* ... */)
}).then(_ => {
    console.log('Thumbnail created locally.')
    metadata.isThumb = true  // We add custom metadata
    const options = {
        destination: filePath,  // Destination is the same as original
        metadata: { metadata: metadata }
    }
    // We overwrite the (bigger) original image but keep the path
    return bucket.upload(/* localThumb */, options)
})
Run Code Online (Sandbox Code Playgroud)