ThinkPHP 是一个基于 PHP 的轻量级 Web 开发框架,它提供了丰富的功能和组件,使得开发者能够快速构建 Web 应用程序。上传图片是 Web 开发中的一个常见需求,通常涉及到文件上传、存储和处理。
在 application/config.php
中配置文件上传的相关参数:
return [
// 文件上传大小限制
'upload_max_filesize' => '10M',
// 文件上传类型限制
'upload_allow_type' => 'image/jpeg,image/png,image/gif',
];
创建一个控制器来处理文件上传逻辑:
namespace app\controller;
use think\Controller;
use think\Request;
class UploadController extends Controller
{
public function upload(Request $request)
{
// 获取上传的文件
$file = $request->file('image');
// 验证文件
if (!$file->validate(['size' => 1024 * 1024 * 10, 'ext' => 'jpg,png,gif'])) {
return json(['code' => 0, 'msg' => '上传失败,文件大小或类型不正确']);
}
// 保存文件
$savePath = './uploads/';
if (!file_exists($savePath)) {
mkdir($savePath, 0777, true);
}
$info = $file->move($savePath);
if ($info) {
return json(['code' => 1, 'msg' => '上传成功', 'data' => ['path' => $info->getSaveName()]]);
} else {
return json(['code' => 0, 'msg' => '上传失败']);
}
}
}
在视图文件中创建一个上传表单:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传图片</title>
</head>
<body>
<form action="/upload/upload" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<button type="submit">上传</button>
</form>
</body>
</html>
原因:
解决方法:
upload_max_filesize
和 upload_allow_type
配置。原因:
解决方法:
原因:
解决方法:
move
方法的第二个参数自定义文件名,如使用时间戳:$saveName = \think\facade\Filesystem::disk('public')->buildUniqueName('uploads/', $file->getOriginalName());
$info = $file->move($savePath, $saveName);
通过以上步骤和解决方法,你可以轻松实现 ThinkPHP 中的图片上传功能,并解决常见的上传问题。
领取专属 10元无门槛券
手把手带您无忧上云