這篇文章主要介紹了thinkphp表單上傳檔案並將檔案路徑儲存到資料庫中的相關資料,需要的朋友可以參考下
上傳單個檔案,此文以上傳圖片為例,上傳效果
建立資料庫upload_img,用於儲存上傳路徑
CREATE TABLE `seminar_upload_img` (`id` int(11) NOT NULL AUTO_INCREMENT,`img_name` varchar(255) DEFAULT NULL COMMENT '圖片名稱',`img_url` varchar(255) DEFAULT NULL COMMENT '圖片路徑',`create_time` text,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8;
在公用設定檔Common/Conf.php中串連資料庫,並配置地址
return array('DB_TYPE'=>'mysql','DB_HOST'=>'127.0.0.1','DB_NAME'=>'seminar','DB_USER'=>'root','DB_PWD'=>'root','DB_PORT'=>3306,'DB_PREFIX'=>'seminar_','DB_CHARSET'=>'utf8','SHOW_PAGE_TRACE'=>true,/*地址替換*/'TMPL_PARSE_STRING'=>array('__UPLOAD__'=>__ROOT__.'/Public/Uploads',),);
視圖檔案Upload/index.html中
<!DOCTYPE html><html><head><title></title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><style type="text/css">#img{height:22px; border:#000 2px solid}#button{height:30px; width:100px;}</style></head><body><p><notemply name="data"><img src="__UPLOAD__/{$data['img_url']}" width="200" height="100"/></notemply></p><p class="result" >上傳允許檔案類型:'jpg', 'gif', 'png', 'jpeg'影像檔後</p><br><form action="{:U('upload/Upload')}" method="post" enctype="multipart/form-data"><input type="file" name="image"/><input type="submit" value="上傳" id="button"></form></body></html>
控制器UploadController.class.php中實現上傳檔案
namespace Home\Controller;use Think\Controller;class UploadController extends Controller {public function index() {$img=M('upload_img');$sel=$img->order('create_time desc')->find();$this->assign('data', $sel);$this->display();}public function upload(){$upload_img=M('upload_img');if(!empty($_FILES)){//上傳單個映像$upload = new \Think\Upload();// 執行個體化上傳類$upload->maxSize = 1*1024*1024 ;// 設定附件上傳大小$upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 設定附件上傳類型$upload->rootPath = 'Public/Uploads/'; // 設定附件上傳根目錄$upload->savePath = ''; // 設定附件上傳(子)目錄$upload->saveName=array('uniqid','');//上傳檔案的儲存規則$upload->autoSub = true;//自動使用子目錄儲存上傳檔案 $upload->subName = array('date','Ymd');// 上傳單個圖片$info = $upload->uploadOne($_FILES['image']);if(!$info) {// 上傳錯誤提示錯誤資訊$this->error($upload->getError());}else{// 上傳成功 擷取上傳檔案資訊$img_url=$info['savepath'].$info['savename'];$data['img_url']=$img_url;$data['img_name']=$info['savename'];$data['create_time']=NOW_TIME;$upload_img->create($data);$result=$upload_img->add();if(!$result){$this->error('上傳失敗!');}else{$this->success('上傳成功');}}}}}