You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Google Picker API将Google Drive文件保存到本地目录?

使用Google Picker API将Google Drive文件保存到本地目录

你当前的代码仅获取了Drive文件的网页链接(alternateLink),该链接无法直接触发本地下载。要实现文件保存到本地,需要获取文件的可下载资源流,具体实现方案如下:

1. 确认基础配置与权限

  • 确保你的Google Cloud项目已启用Google Drive API。
  • 若涉及私有文件,OAuth2授权时需请求https://www.googleapis.com/auth/drive.readonly权限,否则无法读取私有文件内容。

2. 修改Picker逻辑,保留文件ID

Picker返回的file对象包含id属性,这是调用Drive API的核心标识,需在回调中保留:

var picker = new FilePicker({
    apiKey: 'here_is_my_api_key',
    clientId: 'here_is_my_clientid',
    buttonEl: document.getElementById('<%= btnUploadPhotoGD.ClientID %>'),
    onClick: function (file) {
        // 保存文件信息,新增file.id字段
        linksAry.push({ 
            "title": file.title, 
            "url": file.alternateLink, 
            "thumbnail": file.thumbnailLink,
            "id": file.id 
        });
        document.getElementById('<%= linkJSON.ClientID %>').value = JSON.stringify(linksAry);
        bindDriveTable();

        // 触发文件下载
        downloadDriveFile(file.id, file.title);
    }
});

3. 实现下载函数

通过Drive API的files.get接口,设置alt=media参数获取文件二进制内容,再通过前端生成下载链接触发保存:

function downloadDriveFile(fileId, fileName) {
    const xhr = new XMLHttpRequest();
    const requestUrl = `https://www.googleapis.com/drive/v3/files/${fileId}?alt=media&key=here_is_my_api_key`;
    xhr.open('GET', requestUrl);
    xhr.responseType = 'blob'; // 以二进制blob形式接收响应

    xhr.onload = function() {
        if (xhr.status === 200) {
            // 创建临时下载链接
            const blob = xhr.response;
            const downloadUrl = window.URL.createObjectURL(blob);
            const downloadLink = document.createElement('a');
            
            downloadLink.href = downloadUrl;
            downloadLink.download = fileName; // 指定本地保存的文件名
            document.body.appendChild(downloadLink);
            downloadLink.click(); // 触发下载动作

            // 清理临时资源
            window.URL.revokeObjectURL(downloadUrl);
            document.body.removeChild(downloadLink);
        } else {
            console.error('文件下载失败:', xhr.statusText);
        }
    };

    xhr.onerror = function() {
        console.error('请求Drive API出错');
    };

    // 私有文件需添加授权头(替换为用户授权后的access token)
    // xhr.setRequestHeader('Authorization', 'Bearer ' + userAccessToken);
    xhr.send();
}

关键注意事项

  • 私有文件处理:若用户选择未公开的私有文件,仅用API Key请求会返回权限错误,需在用户完成OAuth2授权后,在请求头中添加Authorization: Bearer {access token}。
  • 大文件优化:下载大文件建议使用**可恢复下载(resumable download)**方式,避免超时或内存溢出。
  • API配额:注意Drive API的调用配额,避免超出限制导致请求失败。

内容的提问来源于stack exchange,提问作者Denis Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:50:25