首页 > 开发 > ThinkPHP > 正文

thinkphp 图片上传简单方法

2024-09-09 15:20:10
字体:大 中 小
来源:转载
供稿:网友

1、在default中的Index文件夹中新建一个index.html模板,代码如下:

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
  2. <html> 
  3.  <head> 
  4.   <title> New Document </title> 
  5.   <meta name="Generator" content="EditPlus"> 
  6.   <meta name="Author" content=""> 
  7.   <meta name="Keywords" content=""> 
  8.   <meta name="Description" content=""> 
  9.  </head> 
  10.  <body> 
  11.   <form METHOD=POST action="__URL__/upload" enctype="multipart/form-data" >  
  12.  
  13.  <input type="text" NAME="name"  >   
  14.  
  15.  <input type="text" NAME="email"  >   
  16.  
  17.  <input type="file"  name="photo" >   
  18.  
  19.  <input type="submit" value="保 存" >   
  20.  
  21. </form> 
  22.  </body> 
  23. </html> 

2、在控制器的IndexAction.class.php中执行下面代码

  1. <?php 
  2. // 本文档自动生成,仅供测试运行 
  3. class IndexAction extends Action 
  4. { 
  5.     
  6.     public function index() 
  7.     { 
  8.        $this->display(); 
  9.     } 
  10.  public function upload(){ 
  11.   if(!emptyempty($_FILES)){ 
  12.    $this->_upload(); 
  13.   } 
  14.  } 
  15.  public function _upload(){ 
  16.   import("ORG.Net.UploadFile"); 
  17.   $upload    = new UploadFile(); 
  18.   //设置上传文件大小 
  19.   $upload->maxsize = 3145728; 
  20.   //设置上传文件类型 
  21.   $upload->allowExts = explode(',',"jpg,gif,jpeg,png"); 
  22.   //设置附近上传目录 
  23.   $upload->savePath = "./Tpl/default/Public/image/"; //注意 目录为入口文件的相对路径 
  24.   //设置需要生成缩略图他,仅对图片文件有效 
  25.   //$upload->thumb = true; 
  26.   //设置引用图片类库包路径 
  27.   //$upload->imageClassPath = 'ORG.Net.Image'; 
  28.   //设置需要生成缩略图他的文件后缀 
  29.   //$upload->thumbPrefix ='m_,s_'; //生成2张缩略图 
  30.   //设置缩略图最大宽度 
  31.   //$upload->thumbMaxWidth = '400,100'; 
  32.   //设置缩略图最大高度 
  33.   //$upload->thumbMaxHeight = '400,100'; 
  34.   //设置上传文件规则 
  35.   $upload->saveRule = uniqid; 
  36.   //删除原图 
  37.   $upload->thumbRemoveOrigin = true; 
  38.   if(!$upload->upload()){ 
  39.    //捕获上传异常 
  40.    $this->error($upload->getErrorMsg()); 
  41.   }else{ 
  42.    //取得成功上传文件信息 
  43.    $info   = $upload->getUploadFileInfo(); 
  44.    $this -> success("上传成功"); 
  45.   } 
  46.    
  47.  } 
  48.  
  49. } 
  50. ?> 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选