ThinkPHP 8 自带文件上传与 Filesystem 抽象,比原生 PHP 少写很多代码。这篇实现单图上传:路由、控制器校验、存储到 public 磁盘、返回 URL,前端 jQuery 实时进度。参考:TP8 文件上传。
一、准备工作
# 1. 创建存储软链(把 public/storage 指向 storage/app/public)
php think storage:link
# 2. 确认目录可写
chmod -R 755 storage
chmod -R 755 public/storage
// config/filesystem.php
return [
'default' => 'local',
'disks' => [
'local' => [
'type' => 'local',
'root' => app()->getRootPath() . 'storage',
],
'public' => [
'type' => 'local',
'root' => app()->getRootPath() . 'public/storage',
'url' => '/storage',
'visibility' => 'public',
],
],
];
二、路由
// route/app.php
use think\facade\Route;
Route::post('upload/image', 'Upload/image');
Route::post('upload/images', 'Upload/images');
三、控制器
namespace app\controller;
use think\facade\Filesystem;
use think\response\Json;
use think\Request;
class Upload
{
public function image(Request $request): Json
{
// 1. 取文件
$file = $request->file('image');
if (!$file) {
return json(['code' => 1, 'msg' => '请选择图片']);
}
// 2. 校验:大小、扩展名、真实 MIME
try {
validate([
'image' => 'fileSize:5242880|fileExt:jpg,jpeg,png,gif,webp|fileMime:image/jpeg,image/png,image/gif,image/webp',
], [
'image.fileSize' => '图片不能超过 5MB',
'image.fileExt' => '只支持 jpg/png/gif/webp',
'image.fileMime' => '文件类型不合法',
])->check(['image' => $file]);
} catch (\think\exception\ValidateException $e) {
return json(['code' => 1, 'msg' => $e->getError()]);
}
// 3. 保存到 public 磁盘的 images 目录,文件名自动随机
$savename = Filesystem::disk('public')->putFile('images', $file);
if (!$savename) {
return json(['code' => 1, 'msg' => '保存失败']);
}
// 4. 返回可访问地址
$url = '/storage/' . str_replace('\\', '/', $savename);
return json([
'code' => 0,
'msg' => '上传成功',
'data' => [
'url' => $url,
'path' => $savename,
'size' => $file->getSize(),
'mime' => $file->getMime(),
],
]);
}
}
四、前端页面(带进度)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>TP8 单图上传</title>
<style>
.box { width: 420px; margin: 40px auto; font-family: sans-serif; }
.preview { width: 200px; height: 200px; border: 1px dashed #ccc; display: flex; align-items: center; justify-content: center; color: #999; overflow: hidden; }
.preview img { width: 100%; height: 100%; object-fit: cover; }
.bar { height: 10px; background: #eee; border-radius: 5px; overflow: hidden; margin: 12px 0; }
.bar span { display: block; height: 100%; width: 0; background: #3157d5; transition: width .15s; }
</style>
</head>
<body>
<div class="box">
<div class="preview" id="preview">未选择</div>
<input type="file" id="file" accept="image/*">
<div class="bar"><span id="bar"></span></div>
<p id="tip">0%</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script>
let file = null;
$('#file').on('change', function () {
const f = this.files[0];
if (!f) return;
file = f;
$('#preview').html('<img src="' + URL.createObjectURL(f) + '">');
});
$('#file').on('change', function () {
if (!file) return;
const fd = new FormData();
fd.append('image', file);
$.ajax({
url: '/upload/image',
type: 'POST',
data: fd,
processData: false,
contentType: false,
dataType: 'json',
xhr: function () {
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
const p = Math.round(e.loaded / e.total * 100);
$('#bar').css('width', p + '%');
$('#tip').text(p + '%');
}
});
return xhr;
},
success: function (res) {
if (res.code === 0) {
$('#tip').text('成功:' + res.data.url);
} else {
$('#tip').text('失败:' + res.msg);
}
},
error: function (xhr) {
$('#tip').text('请求失败:' + xhr.status);
}
});
});
</script>
</body>
</html>
五、校验规则说明
| 规则 | 作用 |
|---|---|
fileSize:5242880 | 最大 5MB |
fileExt:jpg,png | 扩展名白名单 |
fileMime:image/jpeg | 真实 MIME 白名单(防改后缀) |
file | 必须是上传文件 |
六、常见问题
| 现象 | 原因 | 解决 |
|---|---|---|
| 413 Request Entity Too Large | Nginx 限制 | client_max_body_size 10m; |
| 返回 500 | 目录不可写 | chmod -R 755 storage |
| 图片 404 | 没做 storage:link | php think storage:link |
| fileSize 校验不生效 | PHP 上传限制更小 | 调 upload_max_filesize |
| URL 带反斜杠 | Windows 路径 | str_replace('\\','/') |
七、总结
TP8 单图上传就四步:$request->file() → validate() 校验 → Filesystem::putFile() → 拼 /storage/ 地址。前端与原生 PHP 完全一样,靠 xhr.upload.onprogress 显示进度。