【问题标题】:What is an alternative to updating an image in firebase storage bucket than deleting and uploaded?除了删除和上传之外,更新 Firebase 存储桶中的图像还有什么替代方法?
【发布时间】:2021-04-28 02:14:43
【问题描述】:

我将博客文章存储在 firebase 数据库中。博客文章可以有图片。我有一个存储桶,用于存储图像,并将 URL 与数据库中的帖子一起保存到图像中。现在我正在编辑帖子。其中一部分涉及上传不同的图像。我不希望图像无限期地堆积在我的存储桶中。我宁愿用新的图像替换旧图像。我就是这样做的:

                const bucket = fbAdmin.storage().bucket('***');
                if (fields.filename) {
                    await bucket.file(fields.filename).delete();
                }
                const result = await bucket.upload(files.image.path, {metadata: {contentType: files.image.type}});

换句话说,我删除旧文件然后上传新文件。

但我必须认为必须有一种更简单的方法来做到这一点。而不是删除和上传,不是有更新功能吗?比如:

bucket.update(files.image.path, {name: oldFileName});

谢谢

【问题讨论】:

    标签: node.js firebase google-cloud-storage firebase-admin


    【解决方案1】:

    您可以直接写入存储桶中的相同路径,而无需先删除文件。

    const bucket = fbAdmin.storage().bucket('***');
    const result = await bucket.upload(files.image.path, {metadata: {contentType: files.image.type}});
    

    如果文件已经存在,这将覆盖它。

    【讨论】:

    • 这不是写入文件的路径。这是在您的计算机上获取文件的路径。
    【解决方案2】:

    虽然 Frank 的解决方案在技术上确实有效,但如果您有任何与您的对象相关联的元数据,他的方法会删除它。

    我发现我可以使用类似的方法来维护元数据。这也保留了自定义元数据。

    const bucket = admin.storage().bucket('***');
    const destObjPath = 'some-path.jpg';
    const fileRef = bucket.file(destObjPath);
    
    // Get the object's existing metadata
    const existingMetadata = (await fileRef.getMetadata())[0];
    
    // Delete checksum and other calculated metadata fields
    delete existingMetadata.crc32c;
    delete existingMetadata.etag;
    delete existingMetadata.md5Hash;
    delete existingMetadata.size;
    delete existingMetadata.timeCreated;
    delete existingMetadata.timeStorageClassUpdated;
    delete existingMetadata.updated;
    
    // Provide the copied metadata along with the object update
    await bucket.upload(files.image.path, {
        destination: destObjPath,
        metadata: existingMetadata
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-20
      • 2020-03-21
      • 2021-09-25
      • 2014-01-31
      • 2019-12-07
      • 2011-02-23
      • 1970-01-01
      相关资源
      最近更新 更多