【问题标题】:Uploading File using googledrive api in php在php中使用googledrive api上传文件
【发布时间】:2014-12-01 01:54:53
【问题描述】:

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

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

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

【问题讨论】:

    标签: php google-drive-api


    【解决方案1】:

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

    <?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);
    ?>
    

    【讨论】:

    • 感谢克劳迪奥的帮助。但是使用 curl 解决了我的问题。
    • 嗨克劳迪奥。你能帮我在它过期后使用我们从凭据获得的刷新令牌获取新的访问令牌。我将带有 curl 的 http Post 发送到'/o/oauth2/token',但它给出了无效请求错误。谢谢!!!!
    • 尝试将您的请求与使用 OAuth 2.0 Playground 发送的请求进行比较:developers.google.com/oauthplayground
    【解决方案2】:

    试试这个:

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

    您可以查看此example of how to insert a file(单击到 PHP 选项卡)。 尝试先上传带有内容的text/plain文件,图片数据可能需要在base64编码后才能添加到内容中。

    【讨论】:

      【解决方案3】:

      API 已更新,文档没有相应更改。所以在
      上面的克劳迪奥评论 “$file = 新的 Google_DriveFile();”
      应该改为
      $file = new Google_Service_Drive_DriveFile();

      【讨论】:

        猜你喜欢
        • 2016-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多