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

使用PHP调用Google Drive API V3操作共享PDF时遇404文件未找到错误

解决Google Drive API V3下载共享PDF时的404 File Not Found错误

核心原因

你的代码中,首次调用files->get()获取文件元数据时未添加supportsAllDrives参数,而共享文件可能存储在共享驱动器(Shared Drive)中,Google Drive API默认不会访问共享驱动器内的资源,导致API无法定位文件返回404。同时导出函数也缺少该关键参数。

修复步骤

1. 修改下载函数,所有文件操作添加supportsAllDrives参数

调用files->get()获取元数据时必须加上该参数,避免第一步就触发404:

public function downloadFile($fileId, $path)
{
    try {
        if(!$this->filesDir) throw new Exception("No directory path set. Please check the configurations.");
        $client = $this->getClient();
        $driveService = new Drive($client);
        // 首次get请求添加supportsAllDrives参数
        $file = $driveService->files->get($fileId, array('supportsAllDrives' => true));
        $fileName = $file->getName();

        $response = $driveService->files->get($fileId, array('alt' => 'media', 'supportsAllDrives' => true));
        $filepath = $path.date('YmdHis').'_'.$fileName;
        $handle = fopen($this->filesDir.$filepath, "w+");
        while (!$response->getBody()->eof()) { 
            fwrite($handle, $response->getBody()->read(1024));
        }
        fclose($handle);
        return $filepath;
    } catch(Exception $e) {
        echo "Error Message: ".$e;
    }
}

2. 修改导出函数,添加supportsAllDrives参数

导出PDF时同样需要指定该参数,确保API能访问共享驱动器内的文件:

public function exportPdf($fileId, $path)
{
    try {
        if(!$this->filesDir) throw new Exception("No directory path set. Please check the configurations.");
        $client = $this->getClient();
        $driveService = new Drive($client);
        // 首次get请求添加supportsAllDrives参数
        $file = $driveService->files->get($fileId, array('supportsAllDrives' => true));
        $fileName = $file->getName();
        $filepath = $path.date('YmdHis').'_'.$fileName;
        // 导出请求添加supportsAllDrives参数
        $response = $driveService->files->export($fileId, 'application/pdf', array('alt' => 'media', 'supportsAllDrives' => true));
        $content = $response->getBody()->getContents();
        if(!empty($content)) {
            file_put_contents($this->filesDir.$filepath, $content);
            return $filepath;
        } else {
            throw new Exception('Empty content');
        }
    }  catch(Exception $e) {
        echo "Error Message: ".$e;
    }
}

3. 确认共享权限配置

  • 确保共享文件时,已将服务账号的邮箱(从Google Cloud控制台服务账号详情中获取)添加为文件协作者(至少拥有查看权限)。
  • 如果采用“任何人有链接可查看”的共享方式,需确保supportsAllDrives参数已正确设置,当前使用的https://www.googleapis.com/auth/drive权限范围足够覆盖该操作。

额外验证点

可先调用files->list()接口搜索目标文件ID,确认API能检索到文件:

$results = $driveService->files->listFiles(array(
    'q' => "id='".$fileId."'",
    'supportsAllDrives' => true,
    'includeItemsFromAllDrives' => true
));

若能检索到文件,说明权限和参数配置正确,再执行下载/导出操作即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:35:36