[英]how to write a google drive download file to a directory using php
Am trying download a google drive files to a directory using the code below. 我正在尝试使用以下代码将Google驱动器文件下载到目录中。 when I run the code it only open the content of the file on the browser as per code below
当我运行代码时,它仅按照以下代码在浏览器中打开文件的内容
// authentication google drive goes here //身份验证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();
Here is how am trying to download it to a directory called destinations 这是尝试将其下载到名为destinations的目录的方法
// Open file handle for output. //打开文件句柄以进行输出。
$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";
here is the error i got 这是我得到的错误
Fatal error: Uncaught Error: Call to a member function eof() on string in C:\\xampp\\htdocs\\download.php 致命错误:未捕获错误:在C:\\ xampp \\ htdocs \\ download.php中的字符串上调用成员函数eof()
If my understanding is correct, how about this modification? 如果我的理解是正确的,那么该修改如何?
getBody()
for $content
. $content
使用getBody()
。
$content->getBody()->eof()
$content->getBody()->read(1024)
In this modification, the filename is also retrieved by Drive API and used for saving the downloaded file. 在此修改中,文件名也可以通过Drive API检索,并用于保存下载的文件。 If you don't want to use it, please remove the script for it.
如果您不想使用它,请删除它的脚本。
$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/
. ./download/
目录。 If I misunderstood your question and this was not the result you want, I apologize. 如果我误解了您的问题,而这不是您想要的结果,我深表歉意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.