使用Node.js将文件上传到Google云端存储(已声明“ bucketName”)

时间:2019-03-09 15:08:10

标签: javascript node.js google-cloud-platform aws-lambda google-cloud-storage

我在AWS Lambda以及笔记本电脑的本地环境中第一次玩Google Cloud Storage。我使用

在Lambda中设置了环境变量

GOOGLE_APPLICATION_CREDENTIALS

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

'bucketName' has already been declared

我已经在Google Cloud中创建了存储桶,并且还启用了API。谁能帮忙修复代码? (无论如何,大部分都来自Google Cloud文档)

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]
}

1 个答案:

答案 0 :(得分:1)

您与bucketName有冲突:

  • 您将其作为uploadFile的参数:

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

    const bucketName = 'mynewbucket-saturday';
    

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