作者 lyh

gx下载文件错误问题

... ... @@ -68,20 +68,36 @@ class FileManageController extends BaseController
if (!isset($this->param['path']) || empty($this->param['path'])) {
$this->response('参数错误:path 参数缺失或为空', Code::SYSTEM_ERROR);
}
// 获取文件名和完整 URL
$username = basename($this->param['path']);
$parsed_url = parse_url($this->param['path']);
$fileUrl = isset($parsed_url['scheme'])
? $this->param['path']
: 'https://file.globalso.com' . $this->param['path'];
// 获取文件头信息
$headers = @get_headers($fileUrl, 1);
if (!$headers || !isset($headers['Content-Length']) || $headers['Content-Length'] <= 0) {
// 使用 cURL 获取文件头信息
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fileUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 不直接输出,而是返回结果
curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头
curl_setopt($ch, CURLOPT_NOBODY, true); // 只请求头部,不下载实际文件
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 跟随重定向
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时时间
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁用 SSL 验证
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$fileSize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
// 检查文件大小和状态码
if ($httpCode != 200 || $fileSize <= 0) {
$this->response('无法获取文件信息或文件不存在', Code::SYSTEM_ERROR);
}
$fileSize = $headers['Content-Length'];
$contentType = $headers['Content-Type'] ?? 'application/octet-stream';
// 获取文件类型
$contentType = 'application/octet-stream'; // 默认类型为二进制流
if (preg_match('/Content-Type: (.+)/i', $response, $matches)) {
$contentType = $matches[1];
}
// 设置响应头
header('Content-Description: File Transfer');
header('Content-Type: ' . $contentType);
... ... @@ -90,11 +106,11 @@ class FileManageController extends BaseController
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Expires: 0');
// 清空所有输出缓冲区
// 清空输出缓冲区
while (ob_get_level() > 0) {
ob_end_clean();
}
// 初始化 cURL
// 初始化 cURL 下载文件
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fileUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 直接输出内容
... ...