php - 使用 CURL 在浏览器中下载文件时遇到问题
问题描述
我有一个我正在尝试解决的问题。问题是使用 CURL 下载文件,并在发生这种情况时在浏览器中向用户提供另存为提示。我可以成功打开文件,但它直接在浏览器中作为字符数据打开。
到目前为止,我已经尝试使用标准的 Content-Type 和 Content-Disposition 标头,但实际上没有产生保存对话提示:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "ftp://server.com/recordings/4_23_2019/CD36FAFA9DFD4DE190B487C503D5A3D2 @ 2_04_28 PM.wav");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $file); #output
curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
$file = curl_exec($ch);
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="CD36FAFA9DFD4DE190B487C503D5A3D2 @ 2_04_28 PM.wav"');
header('Content-Transfer-Encoding: binary');
header('Content-length: ' . filesize($file));
readfile($file);
exit;
}
?>
我相信使用这些标题应该向用户提供保存提示,但我得到的页面是一堆随机字符。
产生的错误:
警告:file_exists() 期望参数 1 是资源,/path/name 中给出的字符串
警告:无法修改标头信息 - 标头已发送
解决方案
这是来自一个项目(不在产品中)的工作代码。
if (file_exists($path)) {
if (is_readable($path)) {
@set_time_limit(900);
$NomFichier = basename($path);
header("Content-Type: application/force-download; name=\"$NomFichier\"");
header("Content-Transfer-Encoding: binary");
header("Content-Disposition: attachment; filename=\"$NomFichier\"");
header("Expires: 0");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
readfile($path);
exit;
} else {
$this->say_error("Access denied for this file.");
}
} else {
$this->say_error("File moved or deleted.");
}
推荐阅读
- reactjs - antd 标签使用 react-router
- python - 这个使用 petl 的 lambda 函数有什么问题?
- github - 只有在 Travis 测试通过后才部署用户 Github 页面
- r - 仅命名列表中许多数据框的一列
- c# - ASP.NET Web API 2 CRUD 操作与实体框架
- java - 使用 @Query 的 2 表查询的 Spring JPA 方法名称
- prefetch - Google Lighthouse 无法识别预连接和 dns-prefetch
- javascript - Vuex - 突变后获取状态
- html - 如何使用脚本中的帖子?
- android - 禁用设置按钮后,Android我的应用程序崩溃