thinkphp Tutorial _php Framework thinkphp (13) "File Upload"

Source: Internet
Author: User
Tags addall bulk insert save file contact form

First, File upload

File uploads need to use the Net.uploadfile class in the Org Class library package, so you have to introduce the class through the import () function

1. Basic functions

That is, the basic function of the ORG.Net.UploadFile class, but some functions (to generate thumbnails for uploaded image files) Must be combined with thinkphp ORG.Util.Image class implementation, but ORG.Util.Image class does not need to be introduced manually, but in the UploadFile class upload method introduced automatically!

• Basically pass (single file upload)

• Batch Upload

Bulk upload relative to basically pass, only need to modify the following form to

    

UploadFile class will automatically identify the bulk upload, so basically the upload and bulk uploads about the UploadFile class operation is the same, mainly the upload after the successful return of the file information is slightly different. The return is a two-dimensional array containing information about the uploaded file (the file information is in an inner array), but basically the returned two-dimensional array contains only one element, while the bulk upload returns a two-dimensional array containing multiple elements! And then affect the uploaded file information saved to the database operations, in fact, there is no difference, anyway, is a two-dimensional array, directly using the AddAll () method BULK Insert can

• Support image generation thumbnail image

If the uploaded file is a picture, you can create a thumbnail to save it

• Custom parameter uploads

• Upload Detection

such as file size, file suffix, file type, and so on. ps, file suffix is not the same as file type

• Support Coverage mode

• Support for upload type, attachment size, upload path definition

• Support for sub-directories to save uploaded files

When you open a subdirectory to save the uploaded file, subdirectories are generated automatically, and the subdirectories are generated in hash and date two, and if it is a date, you can also define the date format

• Support for hash verification of uploaded files

2. Upload the form

    

    In particular, you must add the Enctype= "Multipart/form-data" property to the form, or the form does not support file upload functionality

3. Upload action

For structural optimization, the upload action is divided into two parts, that is, in the Fileaction module, the definition of two private methods, respectively, the Up () method and the Keeptodb () method, and then in the upload action in turn call these two methods!

  

up () method

The main function is to upload files

    

Some of the properties of the Ps,uploadfile class can refer to the source code or manual, but personal advice to see the source code, because the comments are very clear!

#maxSize: The maximum file size of a file upload, in bytes, by default-1, which indicates an unlimited size

#savePath: File Save path (required)

#saveRule: The save rule for uploading a file must be a function name without any parameters, such as time, uniqid, com_create_guid, etc., but it must be guaranteed that the generated file name is unique , and the default is Uniqid. In fact, this is to specify a callback function to generate a unique string as the file name of the saved file, so you can completely customize a callback function, as long as the resulting string is guaranteed to be unique.

#hashType: The hash verification method for the uploaded file is md5_file by default. It can also be sha1_file, as well as specifying a callback function!

#autoCheck: Whether attachments are automatically detected, default is auto-detect, which is a value of true

#uploadReplace: There is a file with the same name overwritten, default is not overwritten, that is, the value is False

#allowExts: Allow upload of file suffix , default is an empty array, do not do suffix check

#allowTypes: Allow upload of file types , default to an empty array, do not do suffix checking

#autoSub: Whether to use a subdirectory to save the file, default is not used, that is, the value is False

The following 3 items are in effect when you open a subdirectory to save the file

#subType: How to create subdirectories, default to hash, can be set to hash or date

#dateFormat:d ate mode when you create a subdirectory, the date format defaults to YMD

#hashLevel: When you create a subdirectory in hash mode, the number of subdirectories layer, default to 1 layer

------

#thumb: If the uploaded file is a picture, whether to generate a thumbnail, default is not generated, that is, the value is False

The following 6 entries take effect when a thumbnail is generated

#thumbMaxWidth: The maximum width of the thumbnail, if more than one generation is generated (based on each graph), separate

#thumbMaxHeight: The maximum height of the thumbnail, if more than one is generated (same as), separated by

#thumbPrefix: thumbnail filename prefix, default is thumb_, if there are multiple (same), then use, separate, otherwise there is no prefix

#thumbFixfix: thumbnail filename suffix, default is empty

#thumbPath: Save path of thumbnail, default is empty, left blank is Savepath

#thumbFile: Thumbnail file name, default is empty, that is, upload the file name plus prefix (specified)

#thumbRemoveOrigin: Whether to delete the original image after the thumbnail is generated, the default is not to delete, that is, the value is False

Set the parameters of the upload, you can call the UploadFile class upload method for attachment upload, if the failure, return false, then you can use geterrormsg Method gets the error message, and if the upload succeeds, returns True, the list of attachment information that was successfully uploaded can be obtained by calling the Getuploadfileinfo method. So the return value of the Getuploadfileinfo method is a two-dimensional array in which the outer element is the uploaded attachment information. Each attachment information is another array that records the following information

#key: Attachment Upload Form name

#savepath: Save path for uploaded files

#name: The original name of the uploaded file, which is the file name saved in the client machine

#savename: The saved name of the uploaded file, which is the file name saved on the server-side machine

#size: Size of uploaded files

#type: The MIME type of the uploaded file

#extension: type of suffix for uploading files

#上传文件的哈希验证字符串

Then you can write to the database by obtaining additional information, usually only savepath, and of course, other information can be written! There are two ways to save the attachment information, one is to save to the current data table (that is, with other information in the form into a table, such as the user name, name, contact, resume attachment savepath into a table), and the second is saved separately to the Annex table (that is, other information in the form, such as user name, name, The contact form is deposited in the information sheet, and the CV attachment Savepath in the attachment table, and a field in the attachment table is associated with the information table.

Keeptodb () method

    

4. Source code

1 <HTML>2     <Head>3         <title>File Upload</title>4     </Head>5     <Body>6         <volistname= ' Files 'ID= ' file '>7             <imgsrc= "__public__/uploads/{$file. File_path}"/>8         </volist>9         <formAction= "__url__/upload"Method= "POST"enctype= "Multipart/form-data">TenUser name:<inputtype= "text"name= "username"/><BR/> OneSelect File:<inputtype= "File"name= "file[]"/><BR/> A                      <inputtype= "File"name= "file[]"/><BR/> -             <inputtype= "Submit"value= "Upload"/> -         </form> the     </Body> - </HTML>
1<?PHP2     classFileactionextendsaction{3          Public functionindex () {4             $File=NewModel (' File ');5 6             $files=$File-Select ();7             8             $this->assign ("Files",$files);9 Ten             $this-display (); One         } A  -          Public functionupload () { -             if(Empty($_files)){ the                 $this->error ("Please select files to upload"); -}Else{ -                 $file=$this-Up (); -  +                 if($this->keeptodb ($file)){ -                     $this->success (' Upload successful '); +}Else{ A                     $this->error (' Write database failed '); at                 } -             } -         } -  -         //File Upload -         Private functionUp () { inImport (' ORG.Net.UploadFile '); -             $upload=NewUploadFile ();//instantiating an upload class to             $upload->maxsize = 3145728;//set attachment upload size +             $upload->allowexts =Array(' jpg ', ' gif ', ' PNG ', ' jpeg ');//set attachment upload type -             $upload->savepath = './public/uploads/';//Set Attachments upload directory the             $upload->saverule= ' uniqid ';//Set Save file name generation method *             $upload->autosub=true;//To open a subdirectory to save a file $             $upload->subtype= ' Date ';//To set the subdirectory name generation methodPanax Notoginseng  - //related to thumbnails the                $upload->thumb=true;//Turn on save thumbnail function +             $upload->thumbmaxwidth= ' 400,200 ';//Set Thumbnail size A             $upload->thumbmaxheight= ' 200,100 '; the  +                $upload->uploadreplace=true; -  $                $upload->thumbprefix= ' M_,s_ ';//set thumbnail filename prefix $  -                $upload->thumbpath= './public/uploads/thumb/';//set thumbnail save path -  the             if(!$upload->upload ()) {//Upload error message -                 $this->error ($upload-geterrormsg ());Wuyi  the}Else{//Upload Successful -                 return $upload->getuploadfileinfo ();//upload successful return to upload file information Wu             } -         } About  $         Private functionKeeptodb ($file){ -             $File=m (' File '); -  -             /** A * Daoteng The data to be inserted into $data[][] +             */ the              for($i= 0;$i<Count($file);$i++){ -  $                 $data[$i[' File_path ']=$file[$i[' Savename ']; the             } the             return $File->addall ($data); the         } the     } -  in?>

thinkphp Tutorial _php Framework thinkphp (13) "File Upload"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.