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

PHP调用Google Drive API上传异常:返回File ID但云端无文件

问题排查与修复方案

核心问题分析

页面输出File ID但Google Drive中无对应文件,根源是代码参数格式错误、冗余代码及潜在配置问题:

1. 文件创建参数格式错误

$driveService->files->create的第二个参数被错误嵌套双层数组(array([...])),导致Google Drive API无法正确解析上传内容,即便返回File ID,实际未完成有效文件上传。

2. 冗余且错误的MIME类型代码

$mimeType=mime_content_type($fileMetadata);完全无效,$fileMetadata是Drive\DriveFile对象而非本地文件路径,mime_content_type无法处理该类型参数,属于无效代码。

3. 远程文件获取的潜在问题

file_get_contents('https://example.com/test.pdf')依赖PHP配置allow_url_fopen开启,若该配置关闭,会获取失败,导致上传空内容或无文件。

4. 目标文件夹ID有效性存疑

需确认parents字段中的文件夹ID225qhcKKyf8Ot0IhrRxRtqgHNTxLV1LiyI是否正确,若ID错误,文件可能被上传至根目录或未关注的文件夹。


修复后的代码

require_once './google-api-php-client/vendor/autoload.php';
use Google\Client;
use Google\Service\Drive;

function uploadBasic()
{
    try {
        $client = new Client();
        $client->setAuthConfig('./google-api-php-client/1710-6c50418be6b2.json');
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        
        // 定义文件元数据
        $fileMetadata = new Drive\DriveFile([
            'parents' => ['225qhcKKyf8Ot0IhrRxRtqgHNTxLV1LiyI'],
            'name' => 'test.pdf',
            'mimeType' => 'application/pdf'
        ]);
        
        // 获取远程文件内容并检查是否成功
        $content = file_get_contents('https://example.com/test.pdf');
        if ($content === false) {
            throw new Exception('无法获取远程文件内容');
        }
        
        // 修复参数格式:使用单层数组
        $file = $driveService->files->create($fileMetadata, [
            'data' => $content,
            'mimeType' => 'application/pdf',
            'uploadType' => 'multipart',
            'fields' => 'id'
        ]);
        
        printf("File ID: %s\n", $file->id);
        return $file->id;
    } catch(Exception $e) {
        echo "Error Message: ".$e->getMessage();
    }   
}

uploadBasic();

额外验证步骤

  • 确认文件夹ID:登录Google Drive进入目标文件夹,复制地址栏末尾的ID替换现有值;
  • 检查PHP配置:确认php.ini中allow_url_fopen = On,若无法修改配置,可改用curl获取远程文件;
  • 验证服务账号权限:将目标文件夹手动共享给1710-6c50418be6b2.json对应的服务账号邮箱,确保拥有写入权限;
  • 排查空文件:检查Google Drive根目录或服务账号的个人Drive空间,是否存在错误上传生成的空test.pdf文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 00:41:03