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

Google Drive Picker+API获取PDF内容空白问题求助

问题:Google Drive API获取PDF后pdf.js能识别页数但内容空白

使用JavaScript结合Google Drive API获取PDF文件时,pdf.js可以正确识别PDF页数,但内容显示空白。确认pdf.js读取TypedArray的功能正常(可处理HTML input选择的本地PDF),之前参考的Stack Overflow方案因API更新失效,尝试用new File()替代new Blob()也没用,不过webViewLink和webContentLink能正常下载预览PDF。

原因分析

核心问题是gapi.client.drive.files.get请求alt: 'media'时,返回的response.body是字符串格式(而非原始二进制数据),直接将其转为Blob会导致二进制内容被错误编码。pdf.js能识别页数是因为文件头信息未完全损坏,但正文内容已无法解析。

解决方法

用fetch替代gapi.client来请求文件的原始二进制数据,fetch可以直接处理二进制响应,避免编码错误。

修改后的代码

async pickerCallback(data) {
    if (data.action === window.google.picker.Action.PICKED) {
        const document = data[window.google.picker.Response.DOCUMENTS][0];
        const fileId = document[window.google.picker.Document.ID];

        try {
            // 用fetch替代gapi.client获取二进制数据
            const response = await fetch(`https://www.googleapis.com/drive/v3/files/${fileId}?alt=media`, {
                headers: {
                    'Authorization': `Bearer ${this.accessToken}`
                }
            });
            if (!response.ok) throw new Error('文件请求失败');
            
            const blob = await response.blob();
            const arrayBuffer = await blob.arrayBuffer();
            const typedarray = new Uint8Array(arrayBuffer);
            
            // 这里正常调用pdf.js的API,示例:
            // pdfjsLib.getDocument({data: typedarray}).promise.then(pdf => {
            //   // 处理PDF,比如渲染页面
            //   pdf.getPage(1).then(page => {
            //     const viewport = page.getViewport({scale: 1.0});
            //     const canvas = document.getElementById('pdf-canvas');
            //     const context = canvas.getContext('2d');
            //     canvas.height = viewport.height;
            //     canvas.width = viewport.width;
            //     page.render({canvasContext: context, viewport: viewport});
            //   });
            // });
        } catch (error) {
            console.error('Error getting file content:', error);
        }
    }
}

注意事项

  • 权限验证:确保你的OAuth Token拥有https://www.googleapis.com/auth/drive.readonly或更高权限,否则会返回403权限错误。
  • 请求端点:使用Drive v3 API的端点https://www.googleapis.com/drive/v3/files/${fileId}?alt=media,确保请求参数alt=media正确添加,用于获取文件的原始内容。

内容的提问来源于stack exchange,提问作者Jessie Ho

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 12:52:35