学习内容:
https://www.kancloud.cn/tpshop/thinkphp5/231659
完全开发手册:
https://www.kancloud.cn/manual/thinkphp5/155159
教程中的代码:https://github.com/phpervip/tp5a
// 控制器定义
// 文件上传使用ThinkPHP5内置的think\File类库,该类库可以轻松实现文件上传到本地服务器,如果需要上传到其它服务器或者平台,则需要后续调用其它类库或者接口。
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\File;
class Upload extends Controller
{
public function index(){
return $this->fetch();
}
// 文件上传提交(单个文件)
public function up(Request $request){
// 获取表单上传文件
$file = $request->file('file');
if(empty($file)){
$this->error('请选择上传的文件');
}
// 移动到框架应用根目录 /public/uploads下
// $info = $file->move(ROOT_PATH.'public'.DS.'uploads');
// 可以在上传之前调用validate方法设置验证规则,例如:
$info = $file->validate(['ext' => 'jpg,png'])->move(ROOT_PATH . 'public' . DS . 'uploads');
// 上传文件验证
$result = $this->validate(
['file' => $file],
['file'=>'require|image:100,100,png'],
['file.require' => '请选择上传文件', 'file.image' => '必须是100*100的PNG格式文件']);
if($info){
$this->success('文件上传成功'.$info->getRealPath());
}else{
$this->error('文件上传失败'.$file->getError());
}
}
public function many(){
return $this->fetch();
}
public function up_many(Request $request){
$files = $request->file('images');
$item = [];
foreach($files as $file){
$info = $file->move(ROOT_PATH.'public'.DS.'uploads');
if($info){
$item[] = $info->getRealPath();
}else{
// 上传失败获取错误信息
$this->error($file->getError());
}
}
$this->success('文件上传成功'.implode('<br/>',$item));
}
}
// 单个文件上传
// 创建模板文件(application/index/view/upload/index.html):
<h2>文件上传示例</h2>
<FORM method="post" enctype="multipart/form-data" class="form" action="{:url('up')}">
选择文件:<INPUT type="file" class="file" name="file"><br/>
<INPUT type="submit" class="btn" value=" 提交 ">
</FORM>
<div class="copyright">
<a title="官方网站" href="http://www.thinkphp.cn">ThinkPHP</a>
<span>V5</span>
<span>{ 十年磨一剑-为API开发设计的高性能框架 }</span>
</div>
// 多个文件上传
// 创建模板文件(application/index/view/upload/many.html):
<h2>文件上传示例</h2>
<FORM method="post" enctype="multipart/form-data" class="form" action="{:url('up_many')}">
选择文件:
<INPUT type="file" class="file" name="images[]"><br/>
<INPUT type="file" class="file" name="images[]"><br/>
<INPUT type="file" class="file" name="images[]"><br/>
<INPUT type="file" class="file" name="images[]"><br/>
<INPUT type="submit" class="btn" value=" 提交 ">
</FORM>
<div class="copyright">
<a title="官方网站" href="http://www.thinkphp.cn">ThinkPHP</a>
<span>V5</span>
<span>{ 十年磨一剑-为API开发设计的高性能框架 }</span>
</div>
validate方法支持的验证规则包括:
验证规则 | 说明 | 参数类型 |
---|---|---|
size | 上传文件最大字节大小 | integer |
ext | 允许上传的文件后缀 | 数组或者字符串 |
type | 允许上传的文件类型 | 数组或者字符串 |
更多的上传文件验证规则:
验证规则 | 说明 |
---|---|
file | 验证是否为File对象 |
image | 验证是否为图像File对象 |
image:width,height[,type] | 验证图像文件的类型和宽高 |
fileExt:zip,doc,… | 验证文件后缀 |
fileMime:image/png,… | 验证文件类型 |
fileSize:1024 | 验证文件大小 |