Angular 之GoogleDrive 串接圖牆

Google Cloud 申請 OAuth

Google Console 畫面
前往 Google Cloud Console 的「憑證」頁面:

建立一個新專案 > 新增專案

啟用API服務

建立憑證 => OAuth用戶端ID

• 確認「OAuth 2.0 用戶端 ID」清單中確實有這組 ID,且沒有被刪除或停用。

• 選取「網頁應用程式」。

• 填寫名稱。

• 當你要使用oauth=> 已授權重先導向 =>
https://developers.google.com/oauthplayground

• 取得Google client_id 用戶端編號

• 「手動新增範圍」的輸入框
資料存取權 => 「新增或移除範圍」
複製並貼上這兩行完整的網址(一行一個):

「更新所選範圍」

「手動新增範圍」的輸入框

1
2
3
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/drive.readonly

獲取到
client_id
project_id
client_secret

安裝 @types/gapi , @types/gapi.client.drive , @types/google.accounts

安裝指令:

1
2
npm install --save-dev @types/gapi @types/gapi.client.drive @types/google.accounts

src/index.html 引入accounts.google.com

1
<script src="https://accounts.google.com/gsi/client" async defer></script>

src/app/services/google-drive.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import { Injectable, inject, signal } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, map } from 'rxjs';
import { environment } from '../../../environment'
export interface DriveFile {
id: string
name: string
mimeType: string
thumbnailLink?: string // 新增:Google Drive 自動產生的縮圖網址
webViewLink?: string // 新增:Google Drive 的檢視網址
}
@Injectable({ providedIn: 'root' })
export class GoogleDriveService {
private http = inject(HttpClient);
// 替換成你的 Client ID
private readonly CLIENT_ID =environment.GOOGLE_CLIENT_ID;
// 權限範圍:drive.file 僅能存取此 App 建立的檔案;若要讀取所有檔案請改用
private readonly SCOPES = 'https://www.googleapis.com/auth/drive.file';

private readonly DRIVE_API_URL = 'https://www.googleapis.com/drive/v3';

private tokenClient!: google.accounts.oauth2.TokenClient;

// 使用 Signal 儲存 Token,完美支援 Zoneless 與 OnPush
accessToken = signal<string | null>(null);

constructor() {
console.log(environment.production ? 'Production' : '開發中');
console.log('GoogleDriveService', environment.GOOGLE_CLIENT_ID);
this.initTokenClient();
}
// 初始化 GAPI 與 GIS
private initTokenClient(): void {
// 確保 gis script 已載入
if (typeof google !== 'undefined') {
// 初始化 GAPI Client (負責呼叫 Drive API)
this.tokenClient = google.accounts.oauth2.initTokenClient({
client_id: this.CLIENT_ID,
scope: this.SCOPES,
callback: (response) => {
if (response.access_token) {
this.accessToken.set(response.access_token);
}
},
});
}
}

// 觸發 Google 登入與授權視窗
login(): void {
if (!this.tokenClient) this.initTokenClient();
this.tokenClient.requestAccessToken({ prompt: 'consent' });
}

// 登出並撤銷 Token
logout(): void {
const token = this.accessToken();
if (token) {
google.accounts.oauth2.revoke(token, () => {
this.accessToken.set(null);
});
}
}

// 取得檔案列表
/*
你在程式中設定的 SCOPES 是 https://googleapis.com。這個權限只允許你的應用程式讀取「由這個應用程式建立或開啟」的檔案,不會顯示你 Google Drive 裡原本就存在的其他檔案。如果你想測試讀取列表是否成功,請先用你的 uploadFile 上傳一個檔案,再按「讀取檔案列表」就能看到它了。
*/
listFiles(): Observable<{ files: DriveFile[] }> {
// console.log('取得檔案列表', files)
const headers = new HttpHeaders({
Authorization: `Bearer ${this.accessToken()}`,
});
const redFilesApi = `${this.DRIVE_API_URL}/files`;
const params = {
pageSize: '10',
fields: 'files(id,name,mimeType,thumbnailLink,webViewLink)',
}
//
console.log('取得檔案列表 params', params)
return this.http.get<{ files: DriveFile[] }>(redFilesApi, {headers, params: params,});
}
// 刪除檔案或資料夾
deleteFile(fileId: string): Observable<void> {
const headers = new HttpHeaders({
Authorization: `Bearer ${this.accessToken()}`,
});
const deleteFileApi = `${this.DRIVE_API_URL}/files/${fileId}`;
return this.http.delete<void>(deleteFileApi, {
headers,
});
}
// 新增:將檔案設為「知道連結的任何人皆可檢視」,以便分享網址
makeFilePublic(fileId: string): Observable<unknown> {
const headers = new HttpHeaders({
Authorization: `Bearer ${this.accessToken()}`,
'Content-Type': 'application/json',
});
const makeFilePublicApi = `${this.DRIVE_API_URL}/files/${fileId}/permissions`;
return this.http.post(
makeFilePublicApi,
{
role: 'reader',
type: 'anyone',
},
{ headers }
);
}
// 建立資料夾 (可選填 parentId 指定上層資料夾)
createFolder(folderName: string, parentId?: string): Observable<DriveFile> {
const headers = new HttpHeaders({
Authorization: `Bearer ${this.accessToken()}`,
'Content-Type': 'application/json',
});

const metadata: { name: string; mimeType: string; parents?: string[] } = {
name: folderName,
mimeType: 'application/vnd.google-apps.folder',
};

// 如果有指定上層資料夾 ID,則建立在該資料夾內;未指定則建立在雲端硬碟根目錄
if (parentId) {
metadata.parents = [parentId];
}

return this.http.post<DriveFile>(`${this.DRIVE_API_URL}/files`, metadata, {
headers,
});
}

// 上傳檔案 (Multipart 上傳範例)
uploadFile(file: File, folderId?: string): Observable<DriveFile> {
const metadata: { name: string; mimeType: string; parents?: string[] } = {
name: file.name,
mimeType: file.type,
};

// 指定上傳目標資料夾
if (folderId) {
metadata.parents = [folderId];
}

const formData = new FormData();
formData.append(
'metadata',
new Blob([JSON.stringify(metadata)], { type: 'application/json' })
);
formData.append('file', file);

const headers = new HttpHeaders({
Authorization: `Bearer ${this.accessToken()}`,
});
// Multipart 上傳,Request Headers 中的 Content-Type: multipart/form-data
const apiUploadFileMultipart = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart';
// 單純上傳檔案內容
const apiuploadFileMedia ='https://www.googleapis.com/upload/drive/v3/files?uploadType=media'
return this.http.post<DriveFile>(
apiUploadFileMultipart,
formData,
{ headers }
);
}
// 取得圖片的本地預覽網址 (Blob URL)
getImagePreviewUrl(fileId: string): Observable<string> {
const headers = new HttpHeaders({
Authorization: `Bearer ${this.accessToken()}`,
});

return this.http
.get(`${this.DRIVE_API_URL}/files/${fileId}`, {
headers,
params: { alt: 'media' }, // 關鍵參數:要求回傳檔案實際內容而非 JSON
responseType: 'blob', // 指定回傳二進位資料
})
.pipe(map((blob) => URL.createObjectURL(blob)));
}
}

ng g c imageArea

src/app/image-area.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import { Component, inject, signal, computed} from '@angular/core'
import { GoogleDriveService, DriveFile } from '../services/google-drive'
@Component({
imports: [],
standalone: true,
selector: 'app-image-area',
styleUrl: './image-area.css',
templateUrl: './image-area.html',
})
export class ImageArea {
driveService = inject(GoogleDriveService);
// 儲存所有檔案與資料夾
files = signal<DriveFile[]>([]);
// 新增:儲存目前預覽的圖片網址與檔名
previewUrl = signal<string | null>(null);
previewFileName = signal<string>('');
// 自動過濾出「資料夾」,供上傳時的下拉選單使用
folders = computed(() =>
this.files().filter(
(f) => f.mimeType === 'application/vnd.google-apps.folder'
)
);

// 取得列表
loadFiles(): void {
this.driveService.listFiles().subscribe({
next: (res) => this.files.set(res.files || []),
error: (err) => console.error('讀取列表失敗', err),
});
}

// 點擊圖片檔案時觸發預覽
onPreviewImage(file: DriveFile): void {
// 釋放上一次產生的本地網址,避免記憶體洩漏
const oldUrl = this.previewUrl();
if (oldUrl) {
URL.revokeObjectURL(oldUrl);
}

this.previewFileName.set(file.name);
this.driveService.getImagePreviewUrl(file.id).subscribe({
next: (url) => this.previewUrl.set(url),
error: (err) => console.error('載入圖片預覽失敗', err),
});
}

// 關閉預覽
closePreview(): void {
const oldUrl = this.previewUrl();
if (oldUrl) {
URL.revokeObjectURL(oldUrl);
}
this.previewUrl.set(null);
}
// 建立資料夾
onCreateFolder(folderName: string): void {
const trimmedName = folderName.trim();
if (!trimmedName) return;

this.driveService.createFolder(trimmedName).subscribe({
next: (newFolder) => {
alert(`資料夾「${newFolder.name}」建立成功!`);
this.loadFiles(); // 建立後自動更新列表
},
error: (err) => console.error('建立資料夾失敗', err),
});
}

// 選擇並上傳檔案
onFileSelected(event: Event, folderId: string): void {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;

// 若 folderId 為空字串則傳入 undefined (存至根目錄)
this.driveService.uploadFile(file, folderId ).subscribe({
next: (uploadedFile) => {
alert(`檔案「${uploadedFile.name}」上傳成功!`);
this.loadFiles(); // 上傳後自動更新列表
input.value = ''; // 清空 input 以便重複選取同一個檔案
},
error: (err) => console.error('上傳檔案失敗', err),
});
}
// 刪除檔案
onDeleteFile(file: DriveFile): void {
if (!confirm(`確定要刪除「${file.name}」嗎?此動作無法復原。`)) {
return;
}

this.driveService.deleteFile(file.id).subscribe({
next: () => {
// 從畫面列表直接移除該項目,不需重新打一次列表 API
this.files.update((list) => list.filter((item) => item.id !== file.id));

// 如果剛好正在預覽這張圖片,一併關閉預覽
if (this.previewFileName() === file.name) {
this.closePreview();
}
},
error: (err) => console.error('刪除失敗', err),
});
}
// 設定公開權限並複製網址
onCopyLink(file: DriveFile): void {
this.driveService.makeFilePublic(file.id).subscribe({
next: () => {
// 優先使用 API 回傳的 webViewLink,若無則組裝標準檢視網址
// (若你希望複製的是「可直接嵌入 <img> 的圖片直連網址」,可改用 `https://googleusercontent.com{file.id}`)
const shareUrl = file.webViewLink || `https://google.com{file.id}/view`;

navigator.clipboard.writeText(shareUrl).then(() => {
alert(`已開啟公開檢視並複製網址:\n${shareUrl}`);
});
},
error: (err) => console.error('設定權限或複製網址失敗', err),
});
}
}

image-area.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<p>圖片上傳</p>
<div class="drive-container">
<!-- 登入 / 登出控制區 -->
<div class="auth-section">
@if (!driveService.accessToken()) {
<button (click)="driveService.login()">登入 Google Drive</button>
} @else {
<button (click)="driveService.logout()">Google Drive登出</button>
}
</div>

<!-- 登入後才顯示操作區塊 -->
@if (driveService.accessToken()) {

<!-- 1. 建立資料夾區塊 -->
<div class="action-box">
<h3>建立資料夾</h3>
<input
type="text"
#folderInput
placeholder="輸入資料夾名稱"
/>
<button (click)="onCreateFolder(folderInput.value); folderInput.value = ''">
建立資料夾
</button>
</div>

<!-- 2. 上傳檔案區塊 -->
<div class="action-box">
<h3>上傳檔案</h3>
<label>
目標位置:
<select #targetFolderSelect>
<option value="">根目錄 (My Drive)</option>
@for (folder of folders(); track folder.id) {
<option [value]="folder.id">📁 {{ folder.name }}</option>
}
</select>
</label>
<label type="button" for="uploadInput" class="uploadInput">
<input
id="uploadInput"
type="file"
(change)="onFileSelected($event, targetFolderSelect.value)"
/>
</label>
<label for="file-upload" class="upload-dropzone">
<div class="upload-icon-wrapper" aria-hidden="true">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" height="24px" width="24px" fill="#1f1f1f"><path d="M6.5,20q-2.27,0-3.89-1.57T1,14.58q0-1.95 1.18-3.47T5.25,9.15q0.63-2.3 2.5-3.72T12,4q2.93,0 4.96,2.04T19,11q1.73,0.2 2.86,1.49T23,15.5q0,1.88-1.31,3.19T18.5,20H13q-0.82,0-1.41-0.59T11,18V12.85L9.4,14.4L8,13l4-4l4,4l-1.4,1.4L13,12.85V18h5.5q1.05,0 1.78-0.73T21,15.5t-0.72-1.78T18.5,13H17V11q0-2.08-1.46-3.54T12,6Q9.93,6 8.46,7.46T7,11H6.5q-1.45,0-2.47,1.02T3,14.5t1.03,2.48T6.5,18H9v2H6.5ZM12,13Z"/></svg>
</div>
<input id="file-upload" type="file" accept=".jpg,.jpeg,.png,.pdf" hidden />
</label>

</div>

<!-- 3. 相簿與檔案格狀列表 -->
<div class="list-box">
<h3>檔案與相簿列表 <button (click)="loadFiles()">重新整理</button></h3>
</div>
<div class="list_picture_row">
@for (item of files(); track item.id) {
<div class="single_img">

<!-- 縮圖或圖示顯示區 -->
<div class="single_img_thum">
@if (item.mimeType === 'application/vnd.google-apps.folder') {
<span style="font-size: 48px;">📁</span>
} @else if (item.thumbnailLink) {
<!-- 直接顯示 Google Drive 提供的縮圖,點擊可看大圖 -->
<img
[src]="item.thumbnailLink"
[alt]="item.name"
referrerpolicy="no-referrer"
(click)="onPreviewImage(item)"
/>
} @else {
<span style="font-size: 48px;">📄</span>
}
</div>

<!-- 檔案名稱 -->
<div class="file_name" [title]="item.name">
{{ item.name }}
</div>
<!-- 操作按鈕區:複製網址 & 刪除 -->
<div style="display: flex; gap: 6px; justify-content: center; border-top: 1px solid #eee; padding-top: 8px;">
@if (item.mimeType !== 'application/vnd.google-apps.folder') {
<button
(click)="onCopyLink(item)"
style="flex: 1; font-size: 12px; padding: 4px; cursor: pointer;"
title="設為公開並複製網址">
複製網址
</button>
}
<button
(click)="onDeleteFile(item)"
style="flex: 1; font-size: 12px; padding: 4px; color: #d32f2f; cursor: pointer;"
title="永久刪除">
刪除
</button>
</div>
</div>
} @empty {
<p>目前沒有檔案或資料夾</p>
}
</div>
}
</div>

image-area.css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
p{
padding: 20px;
}
.drive-container{
padding: 20px;
}
.action-box, .list-box{
display: flex;
align-items: center;
margin-top: 35px;
}
.action-box input ,
.action-box select{
border:2px solid #666;
padding: 12px 8px;
margin-left: 20px;
}
.action-box input[type="file"]
.action-box label{
margin-left: 20px;
}
.auth-section button,.action-box button ,.list-box button {
background-color: #666;
color:#fff;
padding: 12px 8px;
margin-left: 20px;
}
.list_picture_row{
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 16px;
margin-top: 12px;
}
.list_picture_row .single_img{
border: 1px solid #ddd;
border-radius: 8px;
padding: 10px;
text-align: center;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.list_picture_row .single_img .single_img_thum{
height: 120px;
display: flex;
align-items: center;
justify-content:center;
overflow: hidden;
background: #f9f9f9;
border-radius: 4px;
margin-bottom: 8px;
}
.list_picture_row .single_img .single_img_thum img{
width: 100%;
height: 100%;
object-fit: cover;
cursor: pointer;
}

.file_name{
font-size: 13px;
word-break: break-all;
overflow: hidden;
text-overflow:ellipsis;
display: -webkit-box;
line-clamp: 2;
-webkit-line-clamp: 2;
-webkit-box-orient:vertical;
}

/**/
input[type="file"] {
display: none;
}

.upload-dropzone {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
padding: 0px 42px;
border: 2px solid #666;
cursor: pointer;
transition: border-color 0.2s, background-color 0.2s;
text-align: center;
margin-left: 20px;
}

.upload-dropzone:hover {
color:#fff;
border-color: #333;
background-color: #333;
}

.upload-icon-wrapper {
width: 25px;
height: 44px;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 3px;
transition: transform 0.2s, background-color 0.2s, color 0.2s;
}

.upload-dropzone:hover .upload-icon-wrapper {
color: #fff;
transform: translateY(-1px);
}
.upload-dropzone:hover .upload-icon-wrapper svg {
fill: #fff;
}
.upload-svg {
width: 24px;
height: 24px;
}

.upload-title {
font-size: 15px;
font-weight: 600;
color: #0f172a;
}

.upload-hint {
font-size: 13px;
color: #64748b;
margin-top: 4px;
}
先登入