【问题标题】:Write file and then upload to cloud storage - NodeJS写入文件然后上传到云存储 - NodeJS
【发布时间】:2022-11-12 00:37:49
【问题描述】:

我正在尝试在写入文件后将文件上传到我的存储桶,但我不知道该怎么做。

我确认编写文件的代码没问题,因为我在本地对其进行了测试并且工作正常。

由于文件保存在本地,bucket.upload 似乎不起作用。 bucket.file.save 也不起作用

该文件保存在“./public/fileName.xlsx”。

当我使用:

storage.bucket("bucketName").file("bucketFileName").save("./public/fileName.xlsx")

确实有一个文件已上传到存储中,但其内容是我在 .save() 中传递的路径字符串

所以要继续我的问题是:如何编写文件然后将其上传到我的存储桶?

ps:文件为excel工作表

【问题讨论】:

    标签: node.js google-cloud-storage


    【解决方案1】:

    如果您确认文件保存在本地,只是想上传到bucket,可以参考下面的示例代码:

    const {Storage} = require('@google-cloud/storage');
    
    const storage = new Storage();
    // Change to your bucket name
    const bucketName = 'bucket-name';
    
    async function uploadFile(path, filename) {
      // Path where to save the file in Google Cloud Storage.
      const destFileName = `public/${filename}`;
    
      const options = {
        destination: destFileName,
        // Optional:
        // Set a generation-match precondition to avoid potential race conditions
        // and data corruptions. The request to upload is aborted if the object's
        // generation number does not match your precondition. For a destination
        // object that does not yet exist, set the ifGenerationMatch precondition to 0
        // If the destination object already exists in your bucket, set instead a
        // generation-match precondition using its generation number.
        preconditionOpts: {ifGenerationMatch: generationMatchPrecondition},
      };
      // The `path` here is the location of the file that you want to upload.
      await storage.bucket(bucketName).upload(path, options);
      console.log(`${path} uploaded to ${bucketName}`);
    }
    
    uploadFile('./public/fileName.xlsx', 'fileName.xlsx').catch(console.error);
    

    在示例代码中添加了一些 cmets。 欲了解更多信息,您可以查看此documentation

    【讨论】:

      猜你喜欢
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 2021-03-19
      相关资源
      最近更新 更多