【问题标题】:Does Google Drive API Allow us to download public file without authentication?Google Drive API 是否允许我们无需身份验证即可下载公共文件?
【发布时间】:2017-10-31 18:07:08
【问题描述】:
【问题讨论】:
标签:
java
api
file
authentication
google-drive-api
【解决方案1】:
您无需身份验证即可读取公共文件。文件下载的 URL 很简单:https://www.googleapis.com/drive/v3/files/<FILE_ID>?key=<YOUR_API_KEY>&alt=media。
【解决方案2】:
https://www.googleapis.com/drive/v3/files/<FILE_ID>?key=<YOUR_API_KEY>&alt=media 给了我 CORS 错误,所以这就是我所做的:
-
在没有alt=media的情况下调用https://www.googleapis.com/drive/v3/files/<FILE_ID>?key=<YOUR_API_KEY>
-
在响应时读取属性downloadUrl 和mimeType
-
用responseType: arrayBuffer调用downloadUrl
-
使用blob 将arrayBuffer 转换为可以下载的文件
以下关于 Angular 的代码可以完成这项工作:
async downloadZip(): Promise<void> {
try {
const meta = await this.http.get(
'https://www.googleapis.com/drive/v2/files/<FILE_ID>?key=<API_KEY>'
).toPromise() as { downloadUrl: string, mimeType: string };
const arrBuffer = await this.http.get(meta.downloadUrl, { responseType: 'arraybuffer'}).toPromise();
this.saveArrBuffer('testfile', meta.mimeType, arrBuffer);
} catch (e) {
console.log(e);
}
}
saveArrBuffer(fileName: string, type: string, arr: ArrayBuffer): void {
const blob = new Blob([arr], { type });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
我为此苦苦挣扎,我很乐意发布。