ThinkPHP3.1 quick start (19) file Upload

Source: Internet
Author: User
Tags dateformat
More Upload class usage can be completed by setting Upload parameters, which is left for you to explore. Get the upload class ThinkPHP extension provides the file upload class library UploadFile, can be in http://www.thinkphp.cn/extend/224.html download, download the official extension package (http://www.thinkphp.cn/down/253.html) has included the upload extension class. If the upload class Library is downloaded separately, put the decompressed UploadFile. class. php in the ThinkPHP/Extend/Library/ORG/Net/Directory (if not, manually create it.
The upload class of the latest version contains the following functions (some functions need to be combined with other class libraries of the ThinkPHP system ):
  • Basic Upload function
  • Batch upload is supported.
  • Support generating image thumbnails
  • Custom parameter Upload
  • Upload detection (including size, suffix, and type)
  • Supports overwrite Upload
  • Supports definition of the upload type, Attachment size, and upload path.
  • Supports saving uploaded files by hash or date subdirectories
  • Supports dynamic definition of sub-directories to save files
  • Security detection for uploaded images
  • Supports naming rules for uploaded files
  • Supports Hash verification of uploaded files
If you need to use the upload image to generate thumbnails, you also need to download the extended category of image processing.

The upload form does not require special processing. The following is the simplest single file upload form:
Copy the code. Note that the form must be added. Enctype = "multipart/form-data"Attribute to support the file upload function.

The next step of the upload operation is to define the upload operation. we can add the upload operation to the Action controller as follows:
  1. // File Upload
  2. Public function upload (){
  3. Import ('org. Net. uploadfile ');
  4. $ Upload = new UploadFile (); // instantiate the upload class
  5. $ Upload-> maxSize = 3145728; // sets the attachment upload size.
  6. $ Upload-> allowExts = array ('jpg ', 'GIF', 'PNG', 'jpeg '); // you can specify the attachment upload type.
  7. $ Upload-> savePath = './Public/Uploads/'; // sets the attachment upload Directory
  8. If (! $ Upload-> upload () {// upload error message
  9. $ This-> error ($ upload-> getErrorMsg ());
  10. } Else {// Upload successful
  11. $ This-> success ('upload successful! ');
  12. }
  13. }
The file Upload class provided by the copy code system supports the upload security of image files. if an attempt is made to upload illegal image files, the system will prompt "invalid image files ".

To use the upload function for parameter settings, the first step is to instantiate the upload class:
  1. Import ('org. Net. uploadfile ');
  2. $ Upload = new UploadFile (); // instantiate the upload class
Copy the code and set the upload attributes (parameters). the supported Upload parameters include:
MaxSize The maximum file size (in bytes) uploaded by a file is-1 by default.
SavePath File storage path (required)
SaveRule The storage rule for uploaded files must be a function name without any parameters, such as time and uniqid com_create_guid. However, the generated file name must be unique and the default value is uniqid.
HashType Hash verification method for uploaded files. the default value is md5_file.
AutoCheck Whether to automatically detect attachments. the default value is automatic detection.
UploadReplace Whether a file with the same name is overwritten exists
AllowExts The suffix of the file that can be uploaded (leave blank is unlimited). It is set using arrays. the default value is an empty array.
AllowTypes Specifies the file type that can be uploaded. the default value is an empty array.
Thumb Specifies whether to perform thumbnail processing on image files. the default value is false.
ThumbMaxWidth The maximum width of the thumbnail, separated by commas (,).
ThumbMaxHeight The maximum height of the thumbnail, separated by commas (,).
ThumbPrefix The prefix of the thumbnail. the default value is thumb _
ThumbSuffix File suffix of the thumbnail. the default value is null.
ThumbPath The storage path of the thumbnail. if it is left empty, the file upload directory itself will be used.
ThumbFile Specifies the name of the thumbnail file.
ThumbExt Specify the thumbnail extension
ThumbRemoveOrigin Whether to delete the source image after the thumbnail is generated
AutoSub Whether to use subdirectories to save uploaded files
SubType Subdirectory creation method. the default value is hash. it can be set to hash, date, or custom.
SubDir The sub-directory name is valid after the subType is set to custom.
DateFormat Specify the date format when the subdirectory mode is date
HashLevel Sub-directory storage level, which is a layer by default
You can set the upload parameters as follows:
  1. // Set the attachment Upload Directory
  2. $ Upload-> savePath = './Uploads /';
  3. // Set the thumbnail to be generated, which is only valid for image files
  4. $ Upload-> thumb = true;
  5. // Set the file suffix for generating thumbnails
  6. $ Upload-> thumbPrefix ='m _, s _ '; // produce two thumbnails.
  7. // Set the maximum width of the thumbnail.
  8. $ Upload-> thumbMaxWidth = '2017, 50 ';
  9. // Set the maximum height of the thumbnail.
  10. $ Upload-> thumbMaxHeight = '2017, 50 ';
Another way to copy the code is to import the upload parameters while instantiating the code. for example:
  1. Import ('org. Net. uploadfile ');
  2. $ Config ['savepath'] = './Uploads /';
  3. $ Config ['thumb'] = true;
  4. $ Config ['thumbprefix'] ='m _, s _';
  5. $ Config ['thumbmaxwidth'] = '2017, 50 ';
  6. $ Config ['thumbmaxheight'] = '2017, 50 ';
  7. $ Upload = new UploadFile ($ config); // instantiate the upload class and input parameters
Regardless of the method used to copy the code, after setting the upload parameters, you can call the upload method of the UploadFile class to upload the attachment. if the upload fails, false is returned. GetErrorMsgMethod to obtain the error message. if the upload is successful, you can call GetUploadFileInfoMethod to obtain the list of uploaded attachments. The returned value of the getUploadFileInfo method is a two-dimensional array, where each element is the uploaded attachment information. Each attachment is an array that records the following information, including:
Key Name of the form uploaded by the attachment
Savepath Save path of the uploaded file
Name Original name of the uploaded file
Savename Name of the uploaded file
Size Size of the uploaded file
Type MIME type of the uploaded file
Extension Suffix type of the uploaded file
Hash Hash verification string for uploaded files
After the file is uploaded successfully, you can use the attachment information to access other data, for example, save it to the current data table or a separate attachment data table.
For example, the following shows the fields for saving the upload information to the data table:
  1. // Obtain the information of the successfully uploaded File
  2. $ Info = $ upload-> getUploadFileInfo ();
  3. $ Model = M ('photo ');
  4. // Save the current data object
  5. $ Data ['image'] = $ info [0] ['savename'];
  6. $ Data ['create _ time'] = NOW_TIME;
  7. $ Model-> add ($ data );
Copy the image upload sample from the official website to view the upload and display results:


By default, the multifile Upload class supports multifile Upload. you only need to modify the form page:
If you need to upload multiple files, you only need to modify the form
Copy the code
Copy the code or



Two methods of multi-attachment Upload form file Upload class can be automatically identified.
After the upload is successful, use the getUploadFileInfo method to obtain the information of the uploaded attachment.

A single Upload class also provides a single Upload method
  1. Import ("ORG. Net. UploadFile ");
  2. $ Upload = new UploadFile ();
  3. Foreach ($ _ FILES as $ key => $ file ){
  4. If (! Empty ($ file ['name']) {
  5. $ Upload-> autoSub = true;
  6. $ Upload-> subType = 'date ';
  7. $ Info = $ upload-> uploadOne ($ file );
  8. If ($ info) {// Save the attachment information
  9. M ('photo')-> add ($ info );
  10. } Else {// upload error
  11. $ This-> error ($ upload-> getErrorMsg ());
  12. }
  13. }
  14. }
Copy the uploadOne method to upload only one specified file at a time. if the upload succeeds, the returned value of the uploadOne method is the information of the successfully uploaded File. Unlike the getUploadFileInfo method, this file information is a one-dimensional array that only contains information about a single file. If an error occurs, the error message is still obtained through the getErrorMsg method.

The naming rules for uploaded files are used to ensure that files do not conflict or overwrite files. The definition of naming conventions needs to be adjusted according to your business logic, which is not fixed. For example, if you use timestamps to define naming conventions, conflicts may occur when multiple files are uploaded simultaneously (because multiple files can be uploaded within the same second ), therefore, you need to set appropriate Upload naming rules based on your business needs. Here, by the way, the specific usage of the saveRule parameter is described.
I. using functions
If the input string is a function name, the uploaded file name (excluding the file suffix) is dynamically generated using the function. for example:
  1. $ Upload-> saveRule = 'time'; // use the timestamp name
Copy code
  1. $ Upload-> saveRule = 'com _ create_guid '; // Use The GUID sequence name.
You can also use user-defined functions to copy code:
  1. $ Upload-> saveRule = 'myfun'; // use a custom function name.
Copy code 2. directly set the Upload file name
If the input parameter is not a function name, it is directly treated as an upload file name, for example:
  1. $ Upload-> saveRule = time (). '_'. mt_rand ();
Copy code 3. keep the uploaded file name unchanged
If you want to keep the uploaded file name unchanged, you only need to set the naming convention to null. for example:
  1. $ Upload-> saveRule = '';
Generally, it is not recommended to copy the code, because it will overwrite the same file name after uploading.

The sub-directory saveRule is only used to set the file storage rules, and does not involve directories. to save the uploaded files in sub-directories, you can set sub-directories in the following three ways:
I. hash subdirectories
  1. $ Upload-> subType = 'hash ';
  2. $ Upload-> hashLevel = 2;
After you copy the code settings, the first and second letters after the uploaded files are hashed and saved as the first and second sub-directories respectively. If hashLevel is not set, the first-level sub-directory is used by default.
II. date subdirectory
This method is also commonly used, and the date is used as the subdirectory name,
  1. $ Upload-> subType = 'date ';
  2. $ Upload-> dateFormat = 'Y-m-D ';
The copy code dateFormat parameter is used in combination with the date format. if not set, the default value is Ymd.
III. Custom subdirectories
This method is supported by the newly added function as a more flexible method for saving sub-directories.
  1. $ Upload-> subType = 'custom ';
  2. $ Upload-> subDir = get_user_id ();
The advantage of copying code custom subdirectories is that you can dynamically set the subdirectory name. the preceding definition uses the current user ID as the subdirectory name.

The Image extension class is required to generate a thumbnail. make sure that you have the extension class.
Set the following parameters:
  1. // Set the thumbnail to be generated, which is only valid for image files
  2. $ Upload-> thumb = true;
  3. // Set the prefix of the file for which a thumbnail is to be generated
  4. $ Upload-> thumbPrefix ='m _, s _ '; // produce two thumbnails.
  5. // Set the maximum width of the thumbnail.
  6. $ Upload-> thumbMaxWidth = '2017, 50 ';
  7. // Set the maximum height of the thumbnail.
  8. $ Upload-> thumbMaxHeight = '2017, 50 ';
  9. // Set to remove the source image after generating the thumbnail
  10. $ Upload-> thumbRemoveOrigin = true;
The number of front and back suffixes of the Copy code thumbnails must correspond to the number of widths to generate multiple thumbnails.
By default, the generated thumbnail is located in the directory where the file is saved (including subdirectories). You can also specify a uniform path for saving the thumbnail, for example:
  1. $ Upload-> thumbPath = './Uploads/thumb /';
Copy the code. the thumbPath parameter must end.
We can set a uniform file suffix for thumbnails, for example:
  1. // Set the fixed suffix of the thumbnail
  2. $ Upload-> thumbExt = 'jpg ';
For more Upload class usage of the Copy code, you can set the upload parameters, so that you can explore them slowly.

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.