首页 > 解决方案 > 如何使用 php 将谷歌驱动器下载文件写入目录

问题描述

我正在尝试使用下面的代码将谷歌驱动器文件下载到目录。当我运行代码时,它只会按照下面的代码在浏览器上打开文件的内容

//身份验证谷歌驱动器去这里

$file = $service->files->get($fileId);


  $downloadUrl = $file->getDownloadUrl();
    $request = new Google_Http_Request($downloadUrl, 'GET', null, null);
    $httpRequest = $service->getClient()->getAuth()->authenticatedRequest($request);
   echo $content= $httpRequest->getResponseBody();

这是我尝试将其下载到名为destinations的目录的方法

// 打开文件句柄进行输出。

$content = $service->files->get($fileId, array("alt" => "media"));

// Open file handle for output.

$handle = fopen("/download", "w+");

// Until we have reached the EOF, read 1024 bytes at a time and write to the output file handle.

while (!$content->eof()) {
        fwrite($handle, $content->read(1024));
}

fclose($handle);
echo "success";

这是我得到的错误

致命错误:未捕获的错误:调用 C:\xampp\htdocs\download.php 中字符串上的成员函数 eof()

标签: phpgoogle-drive-api

解决方案


  • 您想使用 google/apiclient 和 php 将文件从 Google Drive 下载到特定目录。
  • 您要下载的文件是您的和/或与您共享的。

如果我的理解是正确的,那么这个修改呢?

修改点:

  • getBody()用于$content.
    • $content->getBody()->eof()
    • $content->getBody()->read(1024)

修改后的脚本:

在此修改中,文件名也由 Drive API 检索并用于保存下载的文件。如果您不想使用它,请删除它的脚本。

$fileId = "###"; // Please set the file ID.

// Retrieve filename.
$file = $service->files->get($fileId);
$fileName = $file->getName();

// Download a file.
$content = $service->files->get($fileId, array("alt" => "media"));
$handle = fopen("./download/".$fileName, "w+"); // Modified
while (!$content->getBody()->eof()) { // Modified
    fwrite($handle, $content->getBody()->read(1024)); // Modified
}
fclose($handle);
echo "success";
  • 在上面的脚本中,下载的文件被保存到./download/.

笔记:

  • 通过Drive API的Files:get方法,可以下载除Google Docs(Google Spreadsheet、Google Document、Google Slides等)以外的文件。如果您想下载 Google Docs,请使用文件的方法:导出。请注意这一点。
    • 所以在上面修改过的脚本中,它假设您正在尝试下载除 Google Docs 之外的文件。

参考:

如果我误解了您的问题并且这不是您想要的结果,我深表歉意。


推荐阅读