ThinkPHP5学习笔记:ThinkPHP5图片上传
TP5上传图片其实和上传文件一样的性质
不过PHP一般默认上传文件大小是2m,要上传大图片或者大文件一定要去PHP哪里调默认的设置
TP5上传图片到本地
废话不多说上代码部分走起
· PHP ·
text
<?php
namespace app\index\controller;
use think\Controller;
use think\Validate;
use think\Db;
class Index extends Controller
{
public function index()
{
$photo=Db::table(‘image’);//连接数据库
$D=$photo->where(‘id’,1)->find();
return $this->fetch('index');
}
public function picture()
{
// 获取表单上传文件 例如上传了001.jpg
$file = request()->file('image');
//校验器,判断图片格式是否正确 //validate 验证函数 //这验证是否是图片,定义验证的方法
//['image' => $file]是tp5自己带的图片验证
//['image'=> 'max:2097152']文件限制大小2m max换size也行
if (true !== $this->validate(['image' => $file], ['image' => 'require|image'],['image'=> 'max:2097152'])) {
$this->error('请选择图像文件或者文件大小大于2m');
} else {
// 移动到框架应用根目录/public/uploads/
//ROOT_PATH项目根目录
$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
if ($info) {
// 成功上传后 获取上传信息
//存入相对路径/upload/日期/文件名
//getSaveName是输出文件的位置以及文件名。系统会自动穿件以时间为名的文件夹,然后输出文件夹的名字和图片的名字。
$data = DS . 'uploads' . DS . $info->getSaveName();
//添加到数据库
//data是快递添加
$add=Db::table('image')
->data(['photo'=>$data])
->insert();
$this->success('新增成功');
//模板变量赋值
$this->assign('image', $data);
return $this->fetch('index');
} else {
// 上传失败获取错误信息
echo $file->getError();
}
}
}
}
·模板代码(html)·
text
<!DOCTYPE html>
<html>
<head>
<title>1234</title>
<link
rel="stylesheet"
type="text/css"
href="__ROOT__/index/css/index.css"
/>
</head>
<body>
<form
method="post"
enctype="multipart/form-data"
class="form"
action="{:url('picture')}"
>
选择图像文件:<input
type="file"
class="file"
name="image"
/><br />
<input type="submit" class="btn" value=" 提交 " />
</form>
</body>
</html>