如何将新名称的文件上传到NodeJS中的GCP存储桶

时间:2020-10-13 04:16:25

标签: node.js google-cloud-storage

我的服务器中有一个名为“ space.jpg”的本地文件。

现在我要将这个新名称的文件上传到GCP存储桶。

我可以使用以下代码成功上传该文件:

const myBucket= gc.bucket('my-bucket')
app.post('/create_file', async (req, res, next) => {
   myBucket.upload("space.jpg")
}

我在服务器中的文件结构

  • server.js
  • space.jpg

现在,我想在用户请求时使用随机ID上传此文件。

例如

app.post('/create_file', async (req, res, next) => {
   // spaceId = random string
   // upload space.jpg to myBucket with the name spaceId 
}

如何使用新名称上传?

1 个答案:

答案 0 :(得分:0)

您将要向upload()对象传递第二个参数到UploadOptions。它具有一个名为destination的属性,您可以在其中命名文件上传路径。

const options = {
  destination: bucket.file('/path/to/newFile.jpg'),
};

myBucket.upload("space.jpg", options);

您当然必须提供自己的文件名。