使用流上传GCS对象时如何设置自定义元数据?
Google Cloud Storage流式上传添加自定义元数据解决方案
问题原因分析
- 直接赋值
newFile.metadata无效:该属性是文件对象的现有元数据快照,仅用于读取,无法在上传前定义新对象的元数据。 - 流式上传配置中的元数据格式错误:自定义元数据需要嵌套在
metadata选项的子metadata字段中,而非直接平级设置。
修正后的代码
移除无效的newFile.metadata赋值,并调整流式上传的配置:
// 1 获取存储桶(假设此处逻辑正常) const bucket = gcsGetBucket(storageBucket || GCS_BUCKET_DEFAULT); if (!bucket) throw new Error('Bucket not found or not initialized'); const newFile: File = bucket.file("testFile"); // 2 流式上传函数 const uploadStream = () => new Promise((resolve, reject) => { const passthroughStream = new Stream.PassThrough(); passthroughStream.write(fileToUpload); passthroughStream.end(); passthroughStream .pipe( newFile.createWriteStream({ resumable: false, gzip: true, contentType: fileMimeType, // 正确的元数据格式:自定义元数据嵌套在metadata子对象中 metadata: { metadata: { test2: 'xyz2' } } }), ) .on('error', (err) => { console.warn('error!'); reject(err); }) .on('finish', () => { resolve(true); }); }); // 3 执行上传 const uploadResult = await uploadStream(); // 4 返回响应 res.success = true;
额外说明
如果需要同时设置GCS标准元数据(如cacheControl、contentDisposition),可直接放在外层metadata对象中:
metadata: { cacheControl: 'public, max-age=3600', contentDisposition: 'attachment; filename="testFile.txt"', metadata: { test2: 'xyz2' } }
这样修改后,即可在单次流式上传操作中完成文件上传与自定义元数据的设置,无需后续更新操作。
内容的提问来源于stack exchange,提问作者crivella
相关产品推荐
相关产品推荐

