我正在使用流将我的文件上传到 GCS。
一切正常,但我不知道如何将自定义元数据添加到新创建的对象中。
我可以通过在创建对象后设置元数据来实现所需的结果,如谷歌文档所示(https://github.com/googleapis/nodejs-storage/blob/main/samples/fileSetMetadata.js) ,但这意味着向我的用户添加更新策略,对我来说,更新对象而不是在一个操作中完成所有操作似乎很奇怪。
这是我用来将文件上传到 GCS 的代码:
// 1 get bucket (assume this is working, it returns my bucket)
const bucket = gcsGetBucket(storageBucket || GCS_BUCKET_DEFAULT);
if (!bucket) throw new Error('Bucket not found or not initialized');
const newFile: File = bucket.file("testFile);
**newFile.metadata = { test1: 'xyz1' };**
// 2 function used to upload using passthrough stream
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: { test2: 'xyz2' },**
}),
)
.on('error', (err) => {
console.warn('error!');
reject(err);
})
.on('finish', () => {
resolve(true);
});
});
// 3 upload file
const uploadResult = await uploadStream();
// 4 set response
res.success = true;
我的尝试没有向对象的元数据写入任何内容。
正如您提到的,它的工作原理是将元数据直接设置到文件对象,它将直接修改文件对象的元数据
您可以参考Max888提供的这个[答案][1]
当您想要设置自定义元数据以及 contentType 等时,您需要将整个内容包装为元数据键值,如下所示:
await file.save(html, { metadata: { contentType: "fileMimeType", resumable: false, gzip: true, metadata: { test2: 'xyz2' }, }, });