如何在Angular中不依赖gapi使用Google Drive API v3实现文件下载导出
在Angular中不依赖gapi实现Google Drive文件下载与导出
核心思路
直接调用Google Drive API的REST接口,通过Angular的HttpClient发送请求,带上已获取的access_token作为授权头,无需依赖弃用的gapi库。
前置准备
- 确保你的Angular项目已导入
HttpClientModule(在app.module.ts中导入并添加到imports数组)。 - 已通过
google.accounts.oauth2.initTokenClient获取到有效的access_token,并妥善保存(比如存在组件变量或服务中)。
一、下载普通文件(非Google原生文档)
针对图片、PDF、普通文档等可直接获取内容的文件,使用Drive API的Files.get接口,指定alt=media参数获取文件二进制内容。
1. 封装服务方法
创建GoogleDriveService(或在现有服务中添加):
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class GoogleDriveService { constructor(private http: HttpClient) {} // 获取文件二进制内容 downloadFile(fileId: string, accessToken: string): Observable<Blob> { const apiUrl = `https://www.googleapis.com/drive/v3/files/${fileId}?alt=media`; return this.http.get(apiUrl, { headers: { Authorization: `Bearer ${accessToken}` }, responseType: 'blob' }); } // 可选:获取文件元数据(文件名、类型等) getFileMetadata(fileId: string, accessToken: string): Observable<{ name: string; mimeType: string }> { const apiUrl = `https://www.googleapis.com/drive/v3/files/${fileId}?fields=name,mimeType`; return this.http.get<{ name: string; mimeType: string }>(apiUrl, { headers: { Authorization: `Bearer ${accessToken}` } }); } }
2. 组件中触发下载
在组件中调用服务方法,将Blob转换为可下载链接:
import { Component } from '@angular/core'; import { GoogleDriveService } from './google-drive.service'; @Component({ selector: 'app-drive', templateUrl: './drive.component.html' }) export class DriveComponent { accessToken: string; // 已通过登录流程获取的token constructor(private driveService: GoogleDriveService) {} downloadTargetFile(fileId: string): void { // 先获取文件名,再下载 this.driveService.getFileMetadata(fileId, this.accessToken).subscribe(metadata => { this.driveService.downloadFile(fileId, this.accessToken).subscribe(blob => { const downloadUrl = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = downloadUrl; link.download = metadata.name; // 使用真实文件名 document.body.appendChild(link); link.click(); // 清理资源 window.URL.revokeObjectURL(downloadUrl); document.body.removeChild(link); }); }); } }
二、导出Google原生文档(Docs/Sheets/Slides等)
针对Google Docs、Sheets这类需要转换格式的文件,使用Drive API的Files.export接口,指定目标格式的MIME类型。
1. 常见导出格式MIME类型
- Google Docs → PDF:
application/pdf - Google Docs → Word:
application/vnd.openxmlformats-officedocument.wordprocessingml.document - Google Sheets → Excel:
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - Google Slides → PPT:
application/vnd.openxmlformats-officedocument.presentationml.presentation
2. 封装导出服务方法
在GoogleDriveService中添加:
exportFile(fileId: string, targetMimeType: string, accessToken: string): Observable<Blob> { const encodedMimeType = encodeURIComponent(targetMimeType); const apiUrl = `https://www.googleapis.com/drive/v3/files/${fileId}/export?mimeType=${encodedMimeType}`; return this.http.get(apiUrl, { headers: { Authorization: `Bearer ${accessToken}` }, responseType: 'blob' }); }
3. 组件中触发导出
exportDocToPdf(fileId: string): void { this.driveService.getFileMetadata(fileId, this.accessToken).subscribe(metadata => { const targetFileName = `${metadata.name.split('.')[0]}.pdf`; this.driveService.exportFile(fileId, 'application/pdf', this.accessToken).subscribe(blob => { const downloadUrl = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = downloadUrl; link.download = targetFileName; document.body.appendChild(link); link.click(); window.URL.revokeObjectURL(downloadUrl); document.body.removeChild(link); }); }); }
关键注意事项
- 权限校验:确保申请的scope包含
https://www.googleapis.com/auth/drive(或更严格的drive.readonly,仅需读取时推荐)。 - Token过期处理:如果请求返回401错误,说明token已过期,需调用
this.pageInfo.client.requestAccessToken()重新获取。 - 错误处理:建议在HTTP请求中添加错误捕获(比如
catchError),处理网络异常、权限不足等情况。
内容的提问来源于stack exchange,提问作者Jotan
相关产品推荐
相关产品推荐

