【问题标题】:Problem with upload image to google drive using php使用php将图片上传到谷歌驱动器的问题
【发布时间】:2022-12-15 02:22:49
【问题描述】:

问题是我得到的日志表明文件已创建并从 googleApi 上传,但实际上没有任何变化。下面我把我的上传图片的php代码:

<?php
include '../vendor/autoload.php';

function handleGoogleDrive($file)
{
    //connecting to google drive
    $client = new \Google_Client();
    $client->setApplicationName('Somesite');
    $client->setScopes([\Google_Service_Drive::DRIVE]);
    $client->setAccessType('offline');
    $client->setAuthConfig('./credentials.json');
    $client->setClientId('2445617429-6k99ikago0s0jdh5q5k3o37de6lqtsd3.apps.googleusercontent.com');
    $client->setClientSecret('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');
    $service = new Google_Service_Drive($client);
    //counting amount of files in folder, there is no real reason in doing that
    //it is just a test of connecting
    $folder_id = '1eQtNOJjlA2CalZYb90bEs34IaP6v9ZHM';
    $options = [
        'q' => "'" . $folder_id . "' in parents",
        'fields' => 'files(id, name)'
    ];
    //printing result
    $results = $service->files->listFiles($options);
    echo count($results->getFiles());
    //trying to add file
    $data = file_get_contents("../test.jpg");
    $file = new Google_Service_Drive_DriveFile();
    $file->setName(uniqid(). '.jpg');
    $file->setDescription('A test document');
    $file->setMimeType('image/jpeg');
    $new_file = $service->files->create($file, [
        'data' => $data,
        'mimeType' => 'image/jpeg',
        'uploadType' => 'multipart',
    ]);
    print_r($new_file);
}

【问题讨论】:

  • 我必须为我糟糕的英语水平道歉。不幸的是,我无法理解but nothing actually changes。我可以问一下您当前问题的详细信息吗?
  • @Tanaike,我的意思是该文件仍未上传到 Google 驱动器
  • @Tanaike,我也打印了我的新文件变量,一切看起来都很好,但 Google Drive 仍然是空的
  • 谢谢你的回复。我认为不需要包括'mimeType' =&gt; 'image/jpeg',。但是,我认为您的脚本可以将文件上传到 Google 云端硬盘。所以,我无法理解but Google Drive is still empty。我为此道歉。例如,当你更改示例文件时,情况是否会发生变化?
  • 你能做一个 file.list 并再次检查是否没有创建新文件吗?

标签: php google-api google-drive-api google-api-php-client


【解决方案1】:

这是我用于上传的标准上传代码。

尝试在您的代码中删除 'uploadType' =&gt; 'multipart',

我也看不到您在上传文件时设置文件夹 ID,这意味着它会转到根目录。

// Upload a file to the users Google Drive account
try{
    $filePath = "image.png";
    $folder_id = '1eQtNOJjlA2CalZYb90bEs34IaP6v9ZHM';
    $fileMetadata = new DriveDriveFile();
    $fileMetadata->setName("image.png");
    $fileMetadata->setMimeType('image/png');
    $fileMetadata->setParents(array($folder_id));

    $content = file_get_contents($filePath);
    $mimeType=mime_content_type($filePath);

    $request  = $service->files->create($fileMetadata, array(
        'data' => $content,
        'mimeType' => $mimeType,
        'fields' => 'id'));

    printf("File ID: %s
", $request->id);
}
catch(Exception $e) {
    // TODO(developer) - handle error appropriately
    echo 'Message: ' .$e->getMessage();
}

请记住,如果您使用的是服务帐户,除非您添加要将文件上传到的文件夹,否则文件将上传到服务帐户驱动器帐户。

档案清单

// Print the next 10 events on the user's drive account.
try{


    $optParams = array(
        'pageSize' => 10,
        'fields' => 'files(id,name,mimeType)'
    );
    $results = $service->files->listFiles($optParams);
    $files = $results->getFiles();

    if (empty($files)) {
        print "No files found.
";
    } else {
        print "Files:
";
        foreach ($files as $file) {
            $id = $file->id;

            printf("%s - (%s) - (%s)
", $file->getId(), $file->getName(), $file->getMimeType());
        }
    }
}
catch(Exception $e) {
    // TODO(developer) - handle error appropriately
    echo 'Message: ' .$e->getMessage();
}

【讨论】:

  • 谢谢,代码很棒,唯一的问题是我收到 insufficientParentPermissions 错误
  • 假设您要上传到的目录不在服务帐户驱动器帐户上。您是否授予服务帐户访问权限?它有写权限吗?
  • @DalmTo,是的,我向所有拥有链接的人开放访问权限,另外还授予对服务帐户的访问权限,可能它没有一些写入访问权限
  • 与我共享链接与授予某人访问权限不同。您需要转到 google drive web 应用程序单击共享并获取服务帐户电子邮件地址并将其添加到那里。
【解决方案2】:

使用向我建议的代码,这是完整的解决方案。 (感谢所有帮助过我的人)

<?php
include '../vendor/autoload.php';
function handleGoogleDrive($file)
{
    //connecting to google drive
    $client = new Google_Client();
    $client->setClientId('YOUR ID IN SECRET FILE');
    $client->setClientSecret(YOUR SECRET IN JSON FILE);
    $client->setRedirectUri(YOUR REDIRECT URI);
    //you should register redirect uri
    $client->setApplicationName('Somesite');
    $client->setScopes([Google_Service_Drive::DRIVE]);
    $client->setAuthConfig('./credentials.json');
    $service = new Google_Service_Drive($client);
    try{
        $filePath = "../test.jpg";
        $folder_id = 'YOUR FOLDER ID';
        $fileMetadata = new Google_Service_Drive_DriveFile();
        $fileMetadata->setName("image.png");
        $fileMetadata->setMimeType('image/png');
        $fileMetadata->setParents(array($folder_id));
    
        $content = file_get_contents($filePath);
        $mimeType=mime_content_type($filePath);
    
        $request  = $service->files->create($fileMetadata, array(
            'data' => $content,
            'mimeType' => $mimeType,
            'fields' => 'id'));
    
        printf("File ID: %s
", $request->id);
    }
    catch(Exception $e) {
        echo 'Message: ' .$e->getMessage();
    }
    catch(Exception $e) {
        echo 'Message: ' .$e->getMessage();
    }
    try{


        $optParams = array(
            'pageSize' => 10,
            'fields' => 'files(id,name,mimeType)'
        );
        $results = $service->files->listFiles($optParams);
        $files = $results->getFiles();
    
        if (empty($files)) {
            print "No files found.
";
        } else {
            print "Files:
";
            foreach ($files as $file) {
                $id = $file->id;
    
                printf("%s - (%s) - (%s)
", $file->getId(), $file->getName(), $file->getMimeType());
            }
        }
    }
    catch(Exception $e) {
        // TODO(developer) - handle error appropriately
        echo 'Message: ' .$e->getMessage();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多