This article mainly introduces thinkphp forms for uploading files and saving the file path to the database. For more information, see upload a single file.
Create a database upload_img to save the upload path
Create table 'Seminar _ upload_img '('id' int (11) not null AUTO_INCREMENT, 'IMG _ name' varchar (255) default null comment 'image name ', 'IMG _ url' varchar (255) default null comment 'image path', 'create _ time' text, primary key ('id ')) ENGINE = InnoDB AUTO_INCREMENT = 23 default charset = utf8;
Connect to the database in the Common/Conf. php file and configure the address.
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,/* Address replacement */'tmpl _ PARSE_STRING' => array ('_ UPLOAD _' =>. '/Public/Uploads ',),);
View File Upload/index.html
Supported file Upload types: 'jpg ', 'GIF', 'PNG', and 'jpeg '.
Implement file upload in controller 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 a single image $ Upload = new \ Think \ upload (); // instantiate the upload class $ upload-> maxSize = 1*1024*1024; // Set the attachment upload size $ upload-> exts = array ('jpg ', 'GIF ', 'PNG ', 'jpeg'); // sets the attachment upload type $ upload-> rootPath = 'public/Uploads /'; // Set the root directory for uploading attachments $ upload-> savePath = ''; // Set the attachment upload (sub) directory $ upload-> saveName = array ('uniqid ', ''); // rules for saving uploaded files $ upload-> autoSub = true; // automatically saves uploaded files using subdirectories $ upload-> subName = array ('date ', 'ymmd'); // upload a single image $ info = $ Upload-> uploadOne ($ _ FILES ['image']); if (! $ Info) {// upload error message $ this-> error ($ upload-> getError ());} else {// obtain the information of the uploaded file after the upload is successful $ 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 ('upload failed! ') ;}Else {$ this-> success ('uploaded successfully ');}}}}}
The above section describes how to upload a file in the thinkphp form and save the file path to the database. I hope this will help you. if you have any questions, please leave a message, the editor will reply to you in a timely manner. I would like to thank you for your support for the script home website!