Cloud Storage

創建 Bucket 公開存取

使用 API 上傳檔案

1.需要先新增服務帳務(Service accout )與賦予角色權限

新增金鑰後存成 json

在 IAM 給予 storage 權限(如果點選下方服務帳戶沒辦法只接給予,其角色權限選單內容較少)

需要的話可以先去角色那邊創建特定角色權限

範例:

const { Storage } = require("@google-cloud/storage");
function uploadFile(bucketName, filePath, destFileName) {
  return new Promise(async (resolve, reject) => {
    try {
      const storage = new Storage({ keyFilename: `${__dirname}/../服務帳戶.json` });

      const options = {
        destination: destFileName,
        preconditionOpts: { ifGenerationMatch: 0 }, 
        // ifGenerationMatch 0 時如果上傳的檔案重複,會出錯
        // 因為 Cloud Storage 上名稱相同重複上傳會覆蓋
      };

      await storage.bucket(bucketName).upload(filePath, options);
      resolve({
        success: true,
        bucketName,
        filePath,
      });
    } catch (error) {
      reject(error);
    }
  });
}
module.exports = {
  uploadFile,
};

Last updated