Thinkphp框架实现多文件上传实现代码
直接在php中的多文件上传我有介绍过很多并且也写过专题了,但是在thinkphp中多文件上传还是头一次碰到了,那么这个thinkphp多文件上传与php会有什么区别与共同点呢?下面我来给大家介绍一个Thinkphp框架实现多文件上传吧,希望对各位会有点帮助.
Thinkphp手册中对于多文件上传描述的很清楚,如果需要使用多个文件,只需要修改表单,把如下代码:
<input type='file' name='photo'> 改为:
- <li><input type='file' name='photo1'></li>
- <li><input type='file' name='photo2'></li>
- <li><input type='file' name='photo3'></li>
- </ol>
-
- <li><input type='file' name='photo[]'></li>
- <li><input type='file' name='photo[]'></li>
- <li><input type='file' name='photo[]'></li>
暂且自己的上传表单域为两个,一个上传图片,一个上传视频,字段名为image、video.
html代码如下:
图片:<input type="file" name="image[]">
视频:<input type="file" name="video[]">
model代码:
- protected $info= '';
-
- protected $_auto = array(
- array('image','upload',3,callback),
- array('video','videoupload',3,callback),
- );
- protected function upload(){
- $var = $_FILES['image']['name'];
- import('ORG.Net.UploadFile');
- $upload = new UploadFile();
- $upload->saveRule = time;
- $upload->allowExts = array('jpg', 'gif', 'png', 'zip','flv');
- $upload->thumb = true;
-
- $upload->videopath = './Public/upload/Video/';
- $upload->savePath = './Public/upload/images/';
- $upload->thumbPrefix = '250_115_,150_110_,213_156_';
- $upload->thumbMaxWidth='250,150,213';
- $upload->thumbMaxHeight='115,110,156';
- if(!in_array('',$var) || !in_array('',$_FILES['video']['name'])){
- if(!$upload->upload()) {
- echo $upload->getErrorMsg();die;
- }else{
- $this->info = $upload->getUploadFileInfo();
- if(!in_array('',$var) && !in_array('',$_FILES['video']['name'])){
- return $this->info[1]['savename'];
- }elseif(!in_array('',$var)){
- return $this->info[0]['savename'];
- }else{
- return false;
- }
-
- }
- }else{
- return flase;
- }
- }
-
- protected function videoupload(){
- if(!in_array('',$var) && !in_array('',$_FILES['video']['name'])){
- return $this->info[0]['savename'];
- }elseif(!in_array('',$_FILES['video']['name'])){
- return $this->info[1]['savename'];
- }else{
- return false;
- }
-
- }
文章最后我来分析一下多文件上传原理吧,先来看看html代码:
- <li><input type='file' name='photo[]'></li>
- <li><input type='file' name='photo[]'></li>
- <li><input type='file' name='photo[]'></li>
这种就是把表单变量定义为数组,在php中数组特殊变量它可以存储多个不定长的内容,所以我们就可以自定多文件上传框了,那么在php处理时我们要如何操作,下面看例子.
- protected $_auto = array(
- array('image','upload',3,callback),
- array('video','videoupload',3,callback),
- );
这个是告诉thinkphp是数组变量了,并不需要像原生态的php中来判断遍历数组长度再一个个上传的代码了,因为了thinkphp己经做好了.