假如要在网页上实现对服务器中 my_folder 目录中文件的显示、预览和下载功能,可以通过 PHP 创建一个简单的文件浏览器。示例如下:
1. 创建文件浏览器 PHP 页面
创建一个名为 file_browser.php 的 PHP 文件,内容如下:
<?php
$directory = 'my_folder'; // 指定文件夹
$files = scandir($directory); // 获取目录中的文件
echo "<h1>文件浏览器</h1>";
echo "<ul>";
foreach ($files as $file) {
if ($file !== '.' && $file !== '..') { // 排除当前目录和父目录
$filePath = $directory . '/' . $file;
echo "<li>";
echo "<a href='preview.php?file=" . urlencode($file) . "'>$file</a>"; // 预览链接
echo " <a href='$filePath' download>下载</a>"; // 下载链接
echo "</li>";
}
}
echo "</ul>";
?>
2. 创建文件预览页面
接着,创建一个名为 preview.php 的文件,内容如下:
<?php
// 检查是否提供了 'file' 参数
if (!isset($_GET['file'])) {
echo "未指定文件。";
exit;
}
// 获取文件名
$file = $_GET['file'] ?? null; // 获取文件路径参数,若为空则为null
if (!($file !== null && !empty($file))) {
echo "无效的文件路径。";
}
$filePath = 'my_folder/' . basename($file); // 假设文件在 my_folder 目录下, basename函数提高路径访问的安全性
// 检查文件是否存在
if (!file_exists($filePath)) {
echo "文件不存在。";
exit;
}
// 根据文件类型输出内容
$extension = pathinfo($filePath, PATHINFO_EXTENSION);
echo "<h1>文件预览:$file</h1>";
switch (strtolower($extension)) {
case 'txt':
header('Content-Type: text/plain');
echo "<pre>" . htmlspecialchars(file_get_contents($filePath)) . "</pre>";
break;
case 'jpg':
case 'jpeg':
case 'png':
case 'gif':
header('Content-Type: image/' . $extension);
echo "<img src='$filePath' alt='预览图片' style='max-width: 100%; height: auto;'>";
break;
case 'mp4':
case 'webm':
case 'ogg':
header('Content-Type: video/' . $extension);
echo "<video controls style='max-width: 100%;'><source src='$filePath' type='video/$extension'>你的浏览器不支持视频标签。</video>";
break;
case 'pdf':
header('Content-Type: application/pdf');
echo "<iframe src='$filePath' style='width:100%; height:600px;' frameborder='0'></iframe>";
break;
default:
echo "不支持的文件类型。";
break;
}
?>
3. 访问浏览器页面
-
将
file_browser.php和preview.php文件放在 Apache 的根目录(例如htdocs)下。 -
访问
file_browser.php页面,例如:http://<your_server_ip>/file_browser.php
功能说明
- 文件列表:
file_browser.php会扫描my_folder目录中的文件,并生成一个文件列表。 - 文件预览:点击文件名将调用
preview.php,根据文件类型显示文件内容或预览。 - 下载功能:每个文件旁边都有一个下载链接,用户可以直接下载文件。 效果如下:
通过上述步骤,可以实现一个简单的文件浏览器,允许用户浏览、预览和下载手机服务器 my_folder 中的文件。