php - 如何使用 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()
解决方案
- 您想使用 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 之外的文件。
参考:
如果我误解了您的问题并且这不是您想要的结果,我深表歉意。
推荐阅读
- rust - 如何将结构引用存储在 vec 中并稍后在其他地方使用该结构?
- matlab - 无法满足 fmincon 中的积分容差以解决 ODE 优化问题
- webpack - Webpack 在 css 和 html 中的相对路径错误
- html - 使用 CSS 在另一个容器中居中绝对容器
- android - 试图存储 mutableListOf
到 SharedPreferences 但不能设置默认值 - java - 我可以向 String 类添加新方法吗?
- google-apps-script - 如何使用 Apps 脚本在 google sheet 中提取 pubhtml ID?
- java - 使用 JSTL 在 List 中迭代 Set
- mysql - 如果它大于另一个值,则将值添加到 MySQL 中的行
- python - 如何从 pygresql 中捕获特定异常?