<?php
// 文件上传
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['fileToUpload'])) {
$targetDirectory = '/path_to_non_public_directory/upload/';
$originalFileName = time().$_FILES["fileToUpload"]["name"];
$targetFileName = $targetDirectory . iconv("UTF-8", "GB2312", $originalFileName); // 将文件名转换为 GB2312 编码
// 将文件从临时目录移动到上传目录
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFileName)) {
echo "文件上传成功。";
} else {
echo "文件上传失败。";
}
}
// 文件下载
if (isset($_GET['filename'])) {
$filepath = '/path_to_non_public_directory/upload/' . $_GET['filename'];
if (file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="' . $_GET['filename'] . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
ob_clean();
flush();
readfile($filepath);
exit;
} else {
echo "文件不存在。";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- 其他 head 部分的内容 -->
</head>
<body>
<h2>上传文件</h2>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="上传文件" name="submit">
</form>
<h2>下载文件</h2>
<ul>
<?php
$files = scandir('/path_to_non_public_directory/upload/');
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
echo "<li><a href='?filename=" . urlencode($file) . "'>".iconv("GBK", "UTF-8", $file)."</a></li>";
}
}
?>
</ul>
</body>
</html>