禁用 Google 云存储上的缓存

问题描述 投票:0回答:3

我一直使用GCS来存储我的图像,并使用NodeJS包将这些图像上传到我的存储桶。我注意到,如果我经常更改图像,它会执行以下操作之一:

  • 变了
  • 它提供旧图像
  • 没有改变

尽管正确设置了所有选项,甚至与 GCS 交叉引用,但这似乎是随机发生的。

我像这样上传我的图片:

const options = {
    destination,
    public: true,
    resumable: false,
    metadata: {
      cacheControl: 'no-cache, max-age=0',
    },
  };

  const file = await this.bucket.upload(tempImageLocation, options);
  const { bucket, name, generation } = file[0].metadata;

  const imageUrl = `https://storage.googleapis.com/${bucket}/${name}`;

我已经争论过是使用您在那里看到的基本 URL 还是使用这个:https://storage.cloud.google.com

我似乎不明白我做错了什么以及如何始终提供新鲜的形象。我也尝试过 ?ignoreCache=1 和其他查询参数。

node.js caching google-cloud-platform google-cloud-storage
3个回答
2
投票

你可以尝试将 ?ignoreCache=1 更改为 ?ignoreCache=0。


0
投票

根据官方 API 文档 - 可访问 here - 显示,您不应该需要

await
。这有时可能会影响您的上传。如果您想使用
await
,则需要在声明中将函数设置为
async
,如文档中的第二个示例所示。您的代码应该如下所示。

  const bucketName = 'Name of a bucket, e.g. my-bucket';
  const filename = 'Local file to upload, e.g. ./local/path/to/file.txt';

  const {Storage} = require('@google-cloud/storage');
  const storage = new Storage();

  async function uploadFile() {
    // Uploads a local file to the bucket
    await storage.bucket(bucketName).upload(filename, {
      // Support for HTTP requests made with `Accept-Encoding: gzip`
      gzip: true,
      // By setting the option `destination`, you can change the name of the
      // object you are uploading to a bucket.
      metadata: {
        // Enable long-lived HTTP caching headers
        // Use only if the contents of the file will never change
        // (If the contents will change, use cacheControl: 'no-cache')
        cacheControl: 'public, max-age=31536000',
      },
    });

    console.log(`${filename} uploaded to ${bucketName}.`);
  }

  uploadFile().catch(console.error);

虽然这未经测试,但它应该可以帮助您避免不总是上传图像的问题。

除此之外,正如编辑元数据的官方文档中所述,您可以更改项目使用和管理元数据(包括缓存控制)的方式。这样,您也可以更改缓存配置。

我还想添加以下链接,获取有关如何使用 Node.js 将图像发送到云存储的完整教程,以防您想检查不同的方法。

如果这些信息对您有帮助,请告诉我!


0
投票

这个java代码(抱歉)+ ?ignoreCache=0 帮助我在客户端中正确更新图像(我必须刷新页面/清除缓存才能看到图像)。主要的技巧是

max-age=0
,因为在存储桶上上传/更新图像时有一个 3600 秒的预定义值 https://cloud.google.com/storage/docs/metadata#caching

BlobInfo blobInfo = BlobInfo.newBuilder(bucketName, objectName)
                    .setContentType("application/octet-stream")
                    .setCacheControl("no-storage, max-age=0")
                    .build();
© www.soinside.com 2019 - 2024. All rights reserved.