【问题标题】:Firebase Function - Resize and overwrite existing image on upload to StorageFirebase 功能 - 在上传到存储时调整大小并覆盖现有图像
【发布时间】:2017-12-29 03:29:32
【问题描述】:

所以我按照Google's official sample 创建了一个 Cloud Storage 触发的 Firebase 函数,该函数将从上传的图像创建调整大小的缩略图并将它们也上传到存储中。这里是简化的:

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>"

}

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

然后你会得到两张图像(原始图像和缩略图),我想用缩略图重写现有图像,所以我只有一张带有原始路径的图像。

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

【问题讨论】:

  • 您只想存储缩略图?
  • @BrunoFerreira 是的,我只想要缩略图,但我希望它有原始图像在存储中的路径,基本上是覆盖原始数据
  • 可以尝试获取原图路径,将缩略图上传到原图路径,例如如果原图路径是.../images可以创建缩略图上传到 .../images 路径并删除原始图像,如果您想显示更多内容,我可以创建答案。
  • @BrunoFerreira 我不确定我们是否理解,这个函数是在原始图像(比如说/avatars/zantsu.jpg)上传之后触发的,这个函数创建一个调整大小的图像并上传数据到/avatars/thumb_zantsu.jpg,如果我删除前缀并将拇指上传到/avatars/zantsu.jpg,这将成功覆盖图像但随后函数再次触发,我不知道如何退出它所以它不会重新开始重新上传
  • 你可以得到 /avatars/zantsu.jpg 创建缩略图 avatars/thumb_zantsu.jpg 上传缩略图所以 /avatars/ 路径有两个图像 thumb 和 original 并且当缩略图上传成功时你删除原来/avatars/zantsu.jpg 和 avatars/thumb_zantsu.jpg 仍然只是缩略图,是我在唱歌吗

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


【解决方案1】:

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

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

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

这是测试:

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

if (metadata.isThumb) {
    console.log('Exiting: Already a thumbnail')
    return
}

这是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)
})

【讨论】:

  • 谢谢一百万,我也在寻找一种方法来覆盖图片,您的解决方案效果很好!干杯!
猜你喜欢
  • 2023-04-04
  • 2019-12-13
  • 2019-01-03
  • 1970-01-01
  • 2022-08-18
  • 2020-06-16
  • 2018-09-09
  • 2021-11-30
  • 2021-10-26
相关资源
最近更新 更多