> 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 公開存取

![](https://2356031413-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0u4DAqfidGmTt67qrG%2Fuploads%2FNnhQFvaMKO2dtp0KJrcS%2F%E6%88%AA%E5%9C%96%202022-11-24%20%E4%B8%8B%E5%8D%8812.58.44.png?alt=media\&token=0b6b91f6-518f-436b-8f40-2032bb08dbae)

## 使用 API 上傳檔案

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

![](https://2356031413-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0u4DAqfidGmTt67qrG%2Fuploads%2FiWLBZjB0dhrQaWuRWaue%2F%E6%88%AA%E5%9C%96%202022-11-24%20%E4%B8%8B%E5%8D%8812.35.22.png?alt=media\&token=003b7605-58f7-426b-8733-c9be4169ef27)

新增金鑰後存成 json

<div align="left"><figure><img src="https://2356031413-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0u4DAqfidGmTt67qrG%2Fuploads%2FgWkkHoyH2OIHLqwQP4pp%2F%E6%88%AA%E5%9C%96%202023-12-27%20%E4%B8%8B%E5%8D%885.41.03.png?alt=media&amp;token=6b7b734f-a09d-4da6-9119-c7ac1d043baf" alt="" width="375"><figcaption></figcaption></figure></div>

![](https://2356031413-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0u4DAqfidGmTt67qrG%2Fuploads%2FQ5ZLQoiRQzDGpvA68MMd%2F%E6%88%AA%E5%9C%96%202022-11-24%20%E4%B8%8B%E5%8D%8812.35.38.png?alt=media\&token=207a44f6-83fc-4d89-a2f0-2b5319e7a5eb)

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

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

![](https://2356031413-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0u4DAqfidGmTt67qrG%2Fuploads%2Fv8V69IcTnYOigC2zLAgf%2F%E6%88%AA%E5%9C%96%202022-11-24%20%E4%B8%8B%E5%8D%881.06.10.png?alt=media\&token=e85ec21a-0bf0-48db-bcf0-7771826bb794)

範例：

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

```
