来自 Google Cloud 存储桶的图像不会立即更新

Ion*_*zău 1 javascript caching node.js google-cloud-storage

更新 Google Cloud 存储桶中的图片时,即使图片更新成功,该 url 也会在一段时间内(几分钟,例如 5 分钟左右)提供旧版本。

我们使用的链接如下所示:

https://storage.googleapis.com/<bucket-name>/path/to/images/1.jpg
Run Code Online (Sandbox Code Playgroud)

更新图像的代码的相关部分是:

var storageFile = bucket.file(imageToUpdatePath);
var storageFileStream = storageFile.createWriteStream({
  metadata: {
    contentType: req.file.mimetype
  }
});

storageFileStream.on('error', function(err) {
   ...
});

storageFileStream.on('finish', function() {
  // cloudFile.makePublic after the upload has finished, because otherwise the file is only accessible to the owner:
  storageFile.makePublic(function(err, data) {
    //if(err)
    //console.log(err);
    if (err) {
      return res.render("error", {
        err: err
      });
    }
    ...
  });
});
fs.createReadStream(filePath).pipe(storageFileStream);
Run Code Online (Sandbox Code Playgroud)

这看起来像是 Google Cloud 端的缓存问题。怎么解决呢?更新后如何在请求的url获取更新后的图像?

在 Google Cloud 管理员中,新图像确实正确显示。

Tra*_*rla 5

默认情况下,公共对象缓存最多 60 分钟 - 请参阅缓存控制和一致性。要解决此问题,您应该在创建/上传对象时将对象的缓存控制属性设置为私有。在上面的代码中,这将进入metadata块,如下所示:

var storageFileStream = storageFile.createWriteStream({
  metadata: {
    contentType: req.file.mimetype,
    cacheControl: 'private'
  }
});
Run Code Online (Sandbox Code Playgroud)