dongweiben5229 2019-08-11 12:27
浏览 28
已采纳

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

Am trying download a google drive files to a directory using the code below. 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

$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

// 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

  • 写回答

1条回答 默认 最新

  • dourui9570 2019-08-11 23:34
    关注
    • You want to download a file from Google Drive to the specific directory using google/apiclient with php.
    • The files you want to download are yours and/or shared with you.

    If my understanding is correct, how about this modification?

    Modification point:

    • Please use getBody() for $content.
      • $content->getBody()->eof()
      • $content->getBody()->read(1024)

    Modified script:

    In this modification, the filename is also retrieved by Drive API and used for saving the downloaded file. 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";
    
    • In above script, the downloaded file is saved to the directory of ./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.
      • So in above modified script, it supposes that you are trying to download the files except for Google Docs.

    References:

    If I misunderstood your question and this was not the result you want, I apologize.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?