使用php中的谷歌驱动api上传文件


Uploading File using googledrive api in php

我搜索了如何使用php在googledriveapi上上传文件。我使用了以下方法

$file-setMimetype='image/jpg';
$file->setTitle='abcd'
$service->files->insert($file).

它在谷歌驱动器上插入带有标题和mimetype的文件,但它是空的。我的问题是如何上传文件中包含的实际数据或内容,即如果我想将图像或pdf文件从我的系统上传到谷歌硬盘。如何。请帮助我如何在$data中发送实际数据。$data变量应该包含什么。

最近添加的Quickstart页面中有一个10分钟的教程,介绍如何编写一个完整的PHP应用程序将文件上传到Drive:

<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:'n$authUrl'n'n";
print "Please enter the auth code:'n";
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
      'data' => $data,
      'mimeType' => 'text/plain',
    ));
print_r($createdFile);
?>

试试这个:

$service->files->insert($file, array(
    'data' => $content,
    'mimeType' => $mimeType,        
));

您可以看看这个如何插入文件的示例(单击PHP选项卡)。尝试先上传一个包含内容的text/plain文件,图像数据可能需要在base64中编码,然后才能添加到内容中。

对api进行了更新,文档没有相应更改。关于Claudio在
上面的评论"$file=新的Google_DriveFile();"
应更改为
$file=新的Google_Service_Drive_DriveFile();