ThinkPHP3.2 File Upload

Source: Internet
Author: User
Tags md5 hash sha1 hash
The upload form does not need to be specially processed when using the upload function in ThinkPHP. For example, the following is a form submission with an attachment: formactionindex. phparticipant leuploadenctypemultipartform-datamethodpostinputtypetextnamenameinputtypefilenamephotoinputtyp

The upload form does not need to be specially processed when using the upload function in ThinkPHP. For example, the following is a form submission with attachment upload: form action =/index. php/Article/upload enctype = multipart/form-data method = post input type = text name = name/input type = file name = photo/input typ

Upload form

Using the upload function in ThinkPHP requires no special processing. For example, the following is a form submission with attachment upload:

 
 

Note: To use the upload function, you need to set enctype = "multipart/form-data" for your form"

Multi-file upload support

If you need to upload multiple files, you only need to modify the form

 
 

Change

 
 

Or

 
 

The file upload class of the Multi-attachment upload system can be automatically identified.

Upload operation

Use ThinkPHP to upload filesThink\UploadClass, assuming that the previous form is submitted to the current controller's upload method, let's look at the implementation code of the upload method:

 
 
  1. publicfunction upload(){
  2. $ Upload = new \ Think \ Upload (); // instantiate the upload class
  3. $ Upload-> maxSize = 3145728; // sets the attachment upload size.
  4. $ Upload-> exts = array ('jpg ', 'gif', 'png', 'jpeg '); // you can specify the attachment upload type.
  5. $ Upload-> rootPath = './Uploads/'; // you can specify the root directory for uploading attachments.
  6. $ Upload-> savePath = ''; // sets the attachment upload (sub) directory.
  7. // Upload a file
  8. $info = $upload->upload();
  9. If (! $ Info) {// upload error message
  10. $this->error($upload->getError());
  11. } Else {// upload successful
  12. $ This-> success ('upload successful! ');
  13. }
  14. }

The upload class supports the upload security of image files. If you attempt to upload an illegal image file, the system will promptInvalid Image File. We recommend that you enable the upload function on your server.finfoModule support

Upload Parameters

Before the Upload operation, we can set the Upload attributes. The attributes supported by the Upload class include:

Attribute Description
MaxSize The maximum size (in bytes) of the file to be uploaded. 0 is not limited to the size.
RootPath Root path for file upload and storage
SavePath File Upload path (relative to the root path)
SaveName Storage rules for uploaded files, which can be defined in arrays and strings
SaveExt The storage Suffix of the uploaded file. If this parameter is not set, the original file suffix is used.
Replace Whether the file with the same name is overwritten. The default value is false.
Exts The suffix of the file that can be uploaded (leave blank is unlimited). It is set to an array or a string separated by commas (,). The default value is null.
Mimes The file type that can be uploaded (leave blank is unlimited). It is set using arrays or strings separated by commas (,). The default value is null.
AutoSub The default value of automatically saving uploaded files using subdirectories is true.
SubName Create Sub-directories by using arrays or strings
Hash Whether to generate the file's hash code. The default value is true.
Callback Checks whether a file has a callback. If an array of returned file information exists

The preceding attributes can be passed in two ways:

Instantiate incoming

We can directly input the parameter array during instantiation, for example:

 
 
  1. $config = array(
  2. 'maxSize'=>3145728,
  3. 'rootPath'=>'./Uploads/',
  4. 'savePath'=>'',
  5. 'saveName'=> array('uniqid',''),
  6. 'exts'=> array('jpg','gif','png','jpeg'),
  7. 'autoSub'=>true,
  8. 'subName'=> array('date','Ymd'),
  9. );
  10. $ Upload = new \ Think \ Upload ($ config); // instantiate the upload class

The usage of saveName and subName will be described in detail later.

Dynamic assignment

Supports Dynamic assignment of upload parameters after instantiation, for example:

 
 
  1. $ Upload = new \ Think \ Upload (); // instantiate the upload class
  2. $upload->maxSize =3145728;
  3. $upload->rootPath ='./Uploads/';
  4. $upload->savePath ='';
  5. $upload->saveName = array('uniqid','');
  6. $upload->exts = array('jpg','gif','png','jpeg');
  7. $upload->autoSub =true;
  8. $upload->subName = array('date','Ymd');

The above settings are consistent with the input results of Instantiation.

Upload File Information

After setting the upload parameters, you can callThink\UploadClass upload Method for attachment upload. If the upload fails, false is returned, and the getError method is used to obtain the error message. If the upload is successful, an array of successfully uploaded file information is returned.

 
 
  1. $ Upload = new \ Think \ Upload (); // instantiate the upload class
  2. $ Upload-> maxSize = 3145728; // sets the attachment upload size.
  3. $ Upload-> exts = array ('jpg ', 'gif', 'png', 'jpeg '); // you can specify the attachment upload type.
  4. $ Upload-> rootPath = './Uploads/'; // you can specify the root directory for uploading attachments.
  5. $ Upload-> savePath = ''; // sets the attachment upload (sub) directory.
  6. // Upload a file
  7. $info = $upload->upload();
  8. If (! $ Info) {// upload error message
  9. $this->error($upload->getError());
  10. } Else {// the uploaded file is successfully obtained.
  11. foreach($info as $file){
  12. echo $file['savepath'].$file['savename'];
  13. }
  14. }

Each file information is an array that records the following information, including:

Attribute Description
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
Ext Suffix type of the uploaded file
Md5 The md5 hash of the uploaded file is valid only when the hash setting is enabled.
Sha1 The sha1 hash of the uploaded file is valid only when the hash setting is enabled.

After the file is uploaded successfully, you can use the file information for other data operations, such as saving 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. $model = M('Photo');
  2. // Obtain the information of the successfully uploaded file
  3. $info = $upload->upload();
  4. // Save the current data object
  5. $data['photo']= $info[0]['savename'];
  6. $data['create_time']= NOW_TIME;
  7. $model->add($data);
Upload a single file

The upload method supports Multifile Upload. Sometimes, you only need to upload one file and you can use the uploadOne method provided by the Upload class to upload a single file. For example:

 
 
  1. publicfunction upload(){
  2. $ Upload = new \ Think \ Upload (); // instantiate the upload class
  3. $ Upload-> maxSize = 3145728; // sets the attachment upload size.
  4. $ Upload-> exts = array ('jpg ', 'gif', 'png', 'jpeg '); // you can specify the attachment upload type.
  5. $ Upload-> rootPath = './Uploads/'; // you can specify the root directory for uploading attachments.
  6. // Upload a single object
  7. $info = $upload->uploadOne($_FILES['photo1']);
  8. If (! $ Info) {// upload error message
  9. $this->error($upload->getError());
  10. } Else {// the uploaded file is successfully obtained.
  11. echo $info['savepath'].$info['savename'];
  12. }
  13. }

The difference between the file information returned after the uploadOne method is that there is only one-dimensional array of the information of a single file.

Naming rules for uploaded files

The saveName naming rule is used to ensure that files do not conflict or overwrite files. The naming rule definition can be adjusted according to your business logic, 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 saveName 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. // Use the timestamp name
  2. $upload->saveName ='time';
  3. // Use the GUID sequence name
  4. $upload->saveName ='com_create_guid';

You can also use user-defined functions.

 
 
  1. // Use the custom function name
  2. $upload->saveName ='myfun';

The default naming rule is to use the uniqid function to generate a unique string sequence.

The saveName value supports two methods: array and string. If there is only one parameter or a function without a parameter, you can directly set it using the string. If you need to input additional parameters, you can use the array method, for example:

 
 
  1. // Use the date function to generate a naming rule and input the Y-m-d parameter.
  2. $upload->saveName = array('date','Y-m-d');
  3. // Use an array if multiple parameters need to be input.
  4. $upload->saveName = array('myFun',array('__FILE__','val1','val2'));

If you need to use the original FILE name to upload, you can use _ FILE _ to pass in. Therefore, the final result of the above definition rule isMyFun ('upload filename ', 'val1', 'val2 ')Execution result.

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->saveName = time().'_'.mt_rand();

Indicates that the name of the uploaded file is a combination of a timestamp and a random number.

Of course, if necessary, you can also set a naming rule for uploading files to save a file.

 
 
  1. $upload->saveName ='ThinkPHP';
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->saveName ='';

In general, it is not recommended to keep it unchanged because the same file name will be overwritten after being uploaded.

Save subdirectory

SaveName is only used to set the file storage rules, and does not involve directories. If you want to save the uploaded file's molecular directory, you can setautoSubAndsubNameParameters, for example:

 
 
  1. // Enable subdirectory saving and use the date (Format: Ymd) as the subdirectory
  2. $upload->autoSub =true;
  3. $upload->subName = array('date','Ymd');

You can use a custom function to save data. For example:

 
 
  1. // Enable sub-directory saving and call the custom function get_user_id to generate sub-Directories
  2. $upload->autoSub =true;
  3. $upload->subName ='get_user_id';

Like the saveName parameter, subName can be defined using arrays and strings.

Note: If the get_user_id function is undefined, it will be saved directly with the get_user_id string as the subdirectory name.

Sub-directory storage and file naming rules can be used in combination.

Upload driver

The upload class supports different environments and is implemented through the corresponding upload driver. By default, the Local upload driver is used. Of course, you can also set the current default upload driver type, for example:

 
 
  1. 'FILE_UPLOAD_TYPE'=>'Ftp',
  2. 'UPLOAD_TYPE_CONFIG'=> array(
  3. 'Host' => '192. 168.1.200 ', // server
  4. 'Port' => 21, // port
  5. 'Timeout' => 90, // timeout
  6. 'Username' => 'ftp _ user', // user Name
  7. 'Password' => 'ftp _ pwd', // password ),

Indicates that Ftp is used as the upload driver. The uploaded files are uploaded to the specified remote server through FTP.

You can also specify this parameter when instantiating the upload class, for example:

 
 
  1. $config = array(
  2. 'maxSize'=3145728,
  3. 'rootPath'='./Uploads/',
  4. 'savePath'='',
  5. 'saveName'= array('uniqid',''),
  6. 'exts'= array('jpg','gif','png','jpeg'),
  7. 'autoSub'=true,
  8. 'subName'= array('date','Ymd'),
  9. );
  10. $ftpConfig = array(
  11. 'Host' => '192. 168.1.200 ', // server
  12. 'Port' => 21, // port
  13. 'Timeout' => 90, // timeout
  14. 'Username' => 'ftp _ user', // user Name
  15. 'Password' => 'ftp _ pwd', // password );
  16. $ Upload = new \ Think \ Upload ($ config, 'ftp ', $ ftpConfig); // instantiate the upload class

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.