首页 > 解决方案 > 使用 Node.js 将文件上传到 Google Cloud Storage('bucketName' 已声明)

问题描述

我第一次在 AWS Lambda 中使用Google Cloud Storage,也在我的笔记本电脑上进行本地操作。我使用 Lambda 在 Lambda 中设置了环境变量

GOOGLE_APPLICATION_CREDENTIALS

但是,当我尝试在 zip 中上传 demo.txt 文件时,我得到了

'bucketName' has already been declared

我已经在 Google Cloud 中创建了存储桶并启用了 API。任何人都可以帮助修复代码吗?(反正大部分取自谷歌云文档)

async function uploadFile(bucketName, filename) {
  // [START storage_upload_file]
  // Imports the Google Cloud client library
  const { Storage } = require('@google-cloud/storage');

  // Your Google Cloud Platform project ID
  const projectId = 'apple-ration-27434';

  // Creates a client
  const storage = new Storage();

  var bucketName = 'mybucket-saturday';
  var filename = 'demo.txt';

  // Uploads a local file to the bucket
  await storage.bucket(bucketName).upload(filename, {
    // Support for HTTP requests made with `Accept-Encoding: gzip`
    gzip: true,
    metadata: {
      // Enable long-lived HTTP caching headers
      // Use only if the contents of the file will never change
      // (If the contents will change, use cacheControl: 'no-cache')
      cacheControl: 'public, max-age=31536000',
    },
  });

  console.log(`${filename} uploaded to ${bucketName}.`);
  // [END storage_upload_file]
}

标签: javascriptnode.jsgoogle-cloud-platformaws-lambdagoogle-cloud-storage

解决方案


您有冲突bucketName

  • 您将其作为以下参数uploadFile

    async function uploadFile(bucketName, filename) {
    
  • 您还在本地内部声明它uploadFile

    const bucketName = 'mynewbucket-saturday';
    

您只需要选择一种指定存储桶名称的方法,然后删除另一种。


推荐阅读