ThinkPHP 是一个基于 PHP 的轻量级 Web 开发框架,它简化了 Web 应用的开发过程。在 ThinkPHP 中,获取上传文件是通过框架提供的文件上传类来实现的。
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
class Upload extends Controller
{
public function index(Request $request)
{
if ($request->isPost()) {
// 获取上传文件
$file = $request->file('file');
if ($file) {
// 移动到框架应用目录/public/uploads/ 目录下
$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
if ($info) {
return json(['code' => 1, 'msg' => '上传成功', 'data' => $info->getSaveName()]);
} else {
return json(['code' => 0, 'msg' => $file->getError()]);
}
} else {
return json(['code' => 0, 'msg' => '没有文件被上传']);
}
} else {
return $this->fetch();
}
}
}
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
class Upload extends Controller
{
public function index(Request $request)
{
if ($request->isPost()) {
// 获取上传文件
$files = $request->file('files');
$success = [];
foreach ($files as $file) {
if ($file) {
// 移动到框架应用目录/public/uploads/ 目录下
$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
if ($info) {
$success[] = $info->getSaveName();
} else {
return json(['code' => 0, 'msg' => $file->getError()]);
}
}
}
return json(['code' => 1, 'msg' => '上传成功', 'data' => $success]);
} else {
return $this->fetch();
}
}
}
原因:可能是表单中没有设置 enctype="multipart/form-data"
,或者表单中没有文件上传字段。
解决方法:确保表单中包含 enctype="multipart/form-data"
和文件上传字段。
<form action="/index/upload/index" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
原因:可能是框架配置中限制了文件类型。
解决方法:检查 application/config.php
中的 upload
配置,确保允许上传的文件类型。
'upload' => [
'mimes' => 'jpg,jpeg,png,gif',
'maxSize' => 20480,
],
原因:可能是框架配置中限制了文件大小。
解决方法:检查 application/config.php
中的 upload
配置,调整 maxSize
参数。
'upload' => [
'mimes' => 'jpg,jpeg,png,gif',
'maxSize' => 20480, // 单位为 KB
],
通过以上信息,您应该能够更好地理解和处理 ThinkPHP 中的文件上传问题。