刚桨齐艾起编疼蒲楞卡孩墙斡
D:\phpStudy\PHPTutorial\WWW\tp5\application\index\view\index\index.html:
<h3>文件上传</h3> <form action="{:url('upload')}" method="post" enctype="multipart/form-data"> <input type="file"name="file[]"><br><br> <input type="file"name="file[]"><br><br> <input type="file"name="file[]"><br><br> <button>上传</button> </form>
D:\phpStudy\PHPTutorial\WWW\tp5\application\index\controller\Index.php:
<?php namespace app\index\controller; use think\Controller; class Index extends Controller { public function index() { return $this->fetch(); } //处理上传的文件 public function upload() { // 1.获取文件信息 $files=$this->request->file('file');//返回值为对象 //判断用户是否选择文件 if(empty($files)) { $this->error("没有选择文件"); } // 使用 foreach 遍历文件并上传到 uploads 文件目录 foreach ($files as $file) { //移动到 uploads 目录 $res=$file->move('uploads'); if($res) { // 获取上传文件的保存路径 echo '上传文件的存储路径为:' .$res->getSaveName().'<br>'; } // 上传失败获取错误信息 else { echo $file->getError(); } } } }
执行:
图片成功上传
测试不选文件直接上传
代码:
//判断用户是否选择文件 if(empty($files)) { $this->error("没有选择文件"); }
用于判断用户是否上传文件
限制上传文件的格式
D:\phpStudy\PHPTutorial\WWW\tp5\application\index\controller\Index.php:
<?php namespace app\index\controller; use think\Controller; class Index extends Controller { public function index() { return $this->fetch(); } //处理上传的文件 public function upload() { // 1.获取文件信息 $files=$this->request->file('file');//返回值为对象 //判断用户是否选择文件 if(empty($files)) { $this->error("没有选择文件"); } // 使用 foreach 遍历文件并上传到 uploads 文件目录 foreach ($files as $file) { //移动到 uploads 目录 $res=$file->validate(['ext'=>'jpg,png,gif'])->move('uploads'); if($res) { // 获取上传文件的保存路径 echo '上传文件的存储路径为:' .$res->getSaveName().'<br>'; } // 上传失败获取错误信息 else { $this->error($file->getError()); } } } }
执行:
埂赣磷裂架雄客狠捎柿耍扁埔