Home > Article > Backend Development > thinkphp implements image upload function
There is a very important point here, that is, it is very important to add enctype="multipart/form-data" to the form item, because this is the type that allows you to upload. If there is no him, then It cannot be uploaded. I will explain the other types of enctype in future articles. Here we create a new php file AddAction.class.php, the code is as follows; Many Java users usually use concatenation of two strings, so this is easy to confuse.
class AddAction extends Action{ /** * 说明:ThinkPHP文件上传测试函数 * 版本:1.0 */ public function addChk(){ //导入图片上传类 import("ORG.Net.UploadFile"); //实例化上传类 $upload = new UploadFile(); $upload->maxSize = 3145728; //设置文件上传类型 $upload->allowExts = array('jpg','gif','png','jpeg'); //设置文件上传位置 $upload->savePath = "./Public/Uploads/";//这里说明一下,由于ThinkPHP是有入口文件的,所以这里的./Public是指网站根目录下的Public文件夹 //设置文件上传名(按照时间) $upload->saveRule = "time"; if (!$upload->upload()){ $this->error($upload->getErrorMsg()); }else{ //上传成功,获取上传信息 $info = $upload->getUploadFileInfo(); } //保存表单数据,包括上传的图片 $game = M("Game"); $game->create(); $savename = $info[0]['savename']; //$savepath = $info[0]['savepath']; //$aa = $savepath.$savename; //dump($aa); $imgurl = "http://demo.dutycode.com/Public/Uploads/".$savename;//这里是设置文件的url注意使用.不是+ //dump($imgurl); $data['gamename'] = $_POST['gamename']; $data['gameimg'] = $imgurl; $data['gameinfo'] = $_POST['gameinfo']; $data['gamelink'] = $_POST['gamelink']; $data['publishtime'] = date("Y-m-d H:i:s"); $res = $game->add($data);//写入数据库 if ($res){ $this->redirect("addGame","",2,"添加成功!两秒后跳回"); }else{ $this->redirect("addGame","",2,"失败!两秒后跳回"); } }For more related tutorials, please visit