70 lines
2.0 KiB
PHP
70 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace app\admin\controller;
|
|
|
|
use app\admin\BaseController;
|
|
use think\facade\Request;
|
|
use think\Response;
|
|
|
|
class StorageController extends BaseController
|
|
{
|
|
/**
|
|
* 获取存储文件
|
|
* 用于访问 /storage/ 路径下的静态文件
|
|
* @param string $path 文件路径
|
|
*/
|
|
public function index($path = '')
|
|
{
|
|
// 如果没有传递路径参数,从pathinfo获取
|
|
if (empty($path)) {
|
|
$pathinfo = Request::pathinfo();
|
|
$path = str_replace('storage/', '', $pathinfo);
|
|
}
|
|
|
|
// 防止路径遍历攻击
|
|
$path = str_replace('..', '', $path);
|
|
$path = ltrim($path, '/');
|
|
|
|
// 构建文件完整路径
|
|
$filePath = public_path() . 'storage/' . $path;
|
|
|
|
// 检查文件是否存在
|
|
if (!file_exists($filePath) || !is_file($filePath)) {
|
|
return json([
|
|
'code' => 404,
|
|
'msg' => '文件不存在'
|
|
]);
|
|
}
|
|
|
|
// 获取文件MIME类型
|
|
$mimeType = mime_content_type($filePath);
|
|
if (!$mimeType) {
|
|
// 根据文件扩展名判断MIME类型
|
|
$ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
|
|
$mimeTypes = [
|
|
'jpg' => 'image/jpeg',
|
|
'jpeg' => 'image/jpeg',
|
|
'png' => 'image/png',
|
|
'gif' => 'image/gif',
|
|
'webp' => 'image/webp',
|
|
'mp4' => 'video/mp4',
|
|
'mp3' => 'audio/mpeg',
|
|
'pdf' => 'application/pdf',
|
|
];
|
|
$mimeType = $mimeTypes[$ext] ?? 'application/octet-stream';
|
|
}
|
|
|
|
// 读取文件内容
|
|
$content = file_get_contents($filePath);
|
|
|
|
// 返回文件响应
|
|
return Response::create($content, 'file', 200)
|
|
->header([
|
|
'Content-Type' => $mimeType,
|
|
'Content-Length' => filesize($filePath),
|
|
'Cache-Control' => 'public, max-age=31536000',
|
|
]);
|
|
}
|
|
}
|
|
|