php - 将多个 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);
}
?>
请给出完成结果的方向。
谢谢
解决方案
正如@DalmTo 所说,API 不会让您以 zip 的形式批量下载多个文件,您可以做的是在 Drive 内创建一个文件夹并将该文件夹下载为 zip。
@Tanaike 在这个答案中有大量信息:
将文件夹下载为 Zip Google Drive API
推荐阅读
- python - 使用 Pandas 和 XLSXWriter 在 Excel 工作表中创建表格
- teamcity - 分支规范问题(构建是在分支 XXX 中触发的,它与构建 VCS 根监控的任何分支都不对应)
- javascript - Angular - 类型“{}”缺少类型“任何 []”中的以下属性
- python-3.x - Unable to joint two geopandas data framesm due to 'rtree' error
- r - R:绘制条形图
- docker - Cannot access to secrets .net core with Docker
- oracle - Oracle GoldenGate dblogin failed with GGSIC : no OCI environment handle created
- dafny - 为什么这个前提条件会失败,我不太明白
- vba - Word VBA Rest API Simplybook.me 获得 401 未经授权
- python - 更新字典并使用循环值创建键值对