我正在尝试使用下面的代码将谷歌驱动器文件下载到目录中。当我运行代码时,它仅按照下面的代码在浏览器上打开文件的内容
// 验证谷歌驱动器放在这里
$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();
以下是我尝试将其下载到名为“目的地”的目录的方法
// 打开文件句柄进行输出。
$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 Drive 下载到特定目录。
- 您想要下载的文件是您自己的和/或与您共享的。
如果我的理解是正确的,那么这个修改怎么样?
修改点:
- Please use
getBody()
for $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/
.
Note:
- When the method of Files: get of Drive API, the files except for Google Docs (Google Spreadsheet, Google Document, Google Slides and so on) can be downloaded. If you want to download Google Docs, please use the method of Files: export. Please be careful this.
- 因此,在上面修改后的脚本中,它假设您正在尝试下载除 Google Docs 之外的文件。
参考:
- PHP 快速入门 https://developers.google.com/drive/api/v3/quickstart/php
- 下载文件 https://developers.google.com/drive/api/v3/manage-downloads
- 文件:获取 https://developers.google.com/drive/api/v3/reference/files/get
- 文件:导出 https://developers.google.com/drive/api/v3/reference/files/export
如果我误解了你的问题并且这不是你想要的结果,我深表歉意。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)