# 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,
};

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://easonwang.gitbook.io/web_advance/bu_shu_dao_google_engine__gce/cloud-storage.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
