控制器app\index\controller\Upload.php
//TP5文件上传校验
namespace app\index\controller;
use think\Image;
use think\Request;
/**
* 上传类
*/
class Upload extends Controller
{
//单文件上传
public function index1()
{
return $this->fetch();
}
//多文件上传
public function index2()
{
return $this->fetch();
}
//单文件上传提交
public function up1(Request $request)
{
/*
*第一步校验
*/
//获取表单上传文件
$file = $request->file('file1');//file1:表单name值
//上传验证
$result = $this->validate(['file1'=>$file],['file1'=>'require|image:100,100,png'],['file1.require'=>'请上传格式为100*100的PNG格式文件'],['file1.image'=>'非法图像文件']);//可以不验证图片大小和扩展名,也可以用官网提供的方式验证
if (true !== $result)
{
$this->error($result);
}
/*
*第二步上传,也可以参考官网rule规则,
*这里演示扩展
*/
$info = $file->rule(function ($file) {
return $file->getInfo('type').date('Y-m-d_H-i-s');//文件名,根据项目需要自定义
})->move(ROOT_PATH . 'public' . 'uploads');
}
//多文件上传提交
public function up2(Request $request)
{
$files = $request->file('file2');
foreach($files as $file){
#code....;
}
}
//echo $info->getRealPath();
//echo $info->getExtension();//输出png
//echo $info->getSaveName(); //输出2017/01/05/5.png
//echo $info->getFileName(); //输出5.png
//echo $file->getError(); // 上传失败获取错误信息
}
模板文件app\index\view\upload\up1
<!DOCTYPE html>
<html>
<head>
<title>单文件上传</title>
</head>
<body>
<form action="{:url('up1')}" enctype="multipart/form-data" method="post">
<input type="file" name="file1" /> <br>
<input type="submit" value="上传" />
</form>
</body>
</html>
模板文件app\index\view\upload\up2
<!DOCTYPE html>
<html>
<head>
<title>多文件上传</title>
</head>
<body>
<form action="{:url('up2')}" enctype="multipart/form-data" method="post">
<input type="file" name="file2[]" /> <br>
<input type="file" name="file2[]" /> <br>
<input type="file" name="file2[]" /> <br>
<input type="submit" value="上传" />
</form>
</body>
</html>
网友评论