thinkphp3.2上传方法使用教程

jerry thinkphp 2015年11月19日 收藏
TP3.2出来了,但是原来的上传类被改变,新的类如何使用?这里给大家做个简单教程。
TP3.2出来了,但是原来的上传类被改变,新的类如何使用?这里给大家做个简单教程。
  1. <?php
  2. //名称空间
  3. namespace Open\Controller;
  4. //加载控制器类
  5. use Think\Controller;
  6. //加载上传类
  7. use Think\Upload;

  8. class FileController extends Controller {

  9.     public function test_upload($ftype = 'image') {
  10.         if ($ftype == 'image') {
  11.             $ftype = array('jpg', 'gif', 'png', 'jpeg');
  12.         } else if ($ftype == 'file') {
  13.             $ftype = array('zip', 'doc', 'rar', 'xls');
  14.         }

  15.         $setting = array(
  16.             'mimes' => '', //允许上传的文件MiMe类型
  17.             'maxSize' => 6 * 1024 * 1024, //上传的文件大小限制 (0-不做限制)
  18.             'exts' => $ftype, //允许上传的文件后缀
  19.             'autoSub' => true, //自动子目录保存文件
  20.             'subName' => array('date', 'Y-m-d'), //子目录创建方式,[0]-函数名,[1]-参数,多个参数使用数组
  21.             'rootPath' => './Uploads/', //保存根路径
  22.             'savePath' => '', //保存路径
  23.         );

  24.         /* 调用文件上传组件上传文件 */
  25.         //实例化上传类,传入上面的配置数组
  26.         $this->uploader = new Upload($setting, 'Local');
  27.         $info = $this->uploader->upload($_FILES);

  28.         //这里判断是否上传成功
  29.         if ($info) {
  30.             //// 上传成功 获取上传文件信息
  31.             foreach ($info as &$file) {
  32.                 //拼接出上传目录
  33.                 $file['rootpath'] = __ROOT__ . ltrim($setting['rootPath'], ".");
  34.                 //拼接出文件相对路径
  35.                 $file['filepath'] = $file['rootpath'] . $file['savepath'] . $file['savename'];
  36.             }
  37.             //这里可以输出一下结果,相对路径的键名是$info['upload']['filepath']
  38.             dump($info['upload']);
  39.             exit();
  40.         } else {
  41.             //输出错误信息
  42.             exit($this->uploader->getError());
  43.         }
  44.     }
  45. }
好了,上面的代码已经完成了基本的上传功能,如果你要测试,可以直接将表单提交到这个方法上,就可以看到结果了。

示例:
  1. <form action='__APP__/Open/File/test_upload' ........
这个文件我放在Open模块(原来的分组)下了。