通过Node.js SDK向GCS存储桶上传文件时如何正确添加自定义元数据?
解决GCS上传文件自定义元数据不生效的问题
问题根源
GCS Node.js客户端库对元数据的结构有明确要求:自定义元数据必须嵌套在metadata配置的子metadata对象中。你当前直接将自定义字段放在外层metadata里,会被客户端库判定为非合法配置而忽略——外层metadata仅用于设置GCS内置元数据(如contentType、cacheControl等)。
修正后的代码
const uploadResponse = await GCS.bucket(bucketName).upload(filePath, { destination: filedir + filename, metadata: { // 可选:设置GCS内置元数据(示例) // contentType: 'application/octet-stream', // 自定义元数据必须放在该子对象内 metadata: { custom1: 'customValue1', custom2: 'customValue2' } }, });
验证方式
上传完成后,可通过GCS控制台查看文件元数据,自定义字段会自动被添加x-goog-meta-前缀(如x-goog-meta-custom1);若需在代码中读取,可通过uploadResponse[0].metadata.metadata获取所有自定义元数据集合。
内容的提问来源于stack exchange,提问作者iPhoney
相关产品推荐
相关产品推荐

