> For the complete documentation index, see [llms.txt](https://easonwang.gitbook.io/web_advance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://easonwang.gitbook.io/web_advance/bu_shu_dao_google_engine__gce/cloud-storage.md).

# Cloud Storage

創建 Bucket 公開存取

![](/files/8WnwoLY85imB7dl7Xjlu)

## 使用 API 上傳檔案

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

![](/files/6MZ0JKjN10Bdt0NFzOIz)

新增金鑰後存成 json

<div align="left"><figure><img src="/files/MdEHR6b2ksWvl7UFMvWD" alt="" width="375"><figcaption></figcaption></figure></div>

![](/files/FruQ2yS6UI5gY52WEbEl)

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

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

![](/files/3yZwoolc27VhKGvC8t6f)

範例：

```javascript
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,
};

```
