首页 > 解决方案 > 将多个 Google Drive 文件下载为压缩文件

问题描述

用户登录门户后,将显示 PDF 报告列表。

为了按需下载报告,用户可以选中/取消选中与每个报告关联的框。

例如,

列表中有 10 份报告。用户选择了 7 个报告。点击下载。此工作流程应导致下载包含所有选定报告 (7) 的压缩文件,而不是单独下载每个文件。

上述示例中的这 10 个报告存储在 Google Drive 中。我们将 Google 下载 URL 存储在数据库中。使用这个下载地址我们需要完成上述的结果。

尝试使用 Google Drive API 快速入门参考。错误:第二次尝试将文件保存在文件系统中时出现 403。

PHP cURL 实现在第三轮运行脚本时失败,出现 403 状态码。

基本上,计划是将每个选定的文件保存在文件系统的文件夹中。然后,压缩文件夹并下载 zip。

这是我最近尝试过的,

<?php

define('SAVE_REPORT_DIR', getcwd(). '/pathtosave/'. time());

function fs_report_save($fileUrl) 
{
    static $counter = 1;

    if (!file_exists(SAVE_REPORT_DIR)) {
        mkdir(SAVE_REPORT_DIR, 0777, true);
    }

    //The path & filename to save to.
    $saveTo = SAVE_REPORT_DIR. '/'. time(). '.pdf';

    //Open file handler.
    $fp = fopen($saveTo, 'w+');

    //If $fp is FALSE, something went wrong.
    if($fp === false){
        throw new Exception('Could not open: ' . $saveTo);
    }

    //Create a cURL handle.
    $ch = curl_init($fileUrl);

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    //Pass our file handle to cURL.
    curl_setopt($ch, CURLOPT_FILE, $fp);

    //Timeout if the file doesn't download after 20 seconds.
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);

    //Execute the request.
    curl_exec($ch);

    //If there was an error, throw an Exception
    if(curl_errno($ch)){
        throw new Exception(curl_error($ch));
    }

    //Get the HTTP status code.
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    //Close the cURL handler.
    curl_close($ch);

    //Close the file handler.
    fclose($fp);

    if($statusCode == 200){
        echo 'File: '. $saveTo .'. Downloaded!<br>';
    } else{
        echo "Status Code: " . $statusCode;
    }
}

$reports = array(
    'https://drive.google.com/uc?id=a&export=download',
    'https://drive.google.com/uc?id=b&export=download',
    'https://drive.google.com/uc?id=c&export=download'
);

foreach($reports as $report) {
    fs_report_save($report);
}

?>

请给出完成结果的方向。

谢谢

标签: phpcurlgoogle-drive-apigoogle-api-php-client

解决方案


正如@DalmTo 所说,API 不会让您以 zip 的形式批量下载多个文件,您可以做的是在 Drive 内创建一个文件夹并将该文件夹下载为 zip。

@Tanaike 在这个答案中有大量信息:

将文件夹下载为 Zip Google Drive API


推荐阅读