繁体   English   中英

如何使用php将Google驱动器下载文件写入目录

[英]how to write a google drive download file to a directory using php

我正在尝试使用以下代码将Google驱动器文件下载到目录中。 当我运行代码时,它仅按照以下代码在浏览器中打开文件的内容

//身份验证Google驱动器转到此处

$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()

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

如果我的理解是正确的,那么该修改如何?

修改点:

  • 请对$content使用getBody()
    • $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的“文件:获取”方法时,可以下载Google Docs(Google电子表格,Google文档,Google幻灯片等)以外的文件。 如果要下载Google文档,请使用“文件:导出”方法。 请注意这一点。
    • 因此,在上面修改的脚本中,它假定您正在尝试下载除Google文档以外的文件。

参考文献:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM