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\Upload
Class, 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:
publicfunction upload(){
$ Upload = new \ Think \ Upload (); // instantiate the upload class
$ Upload-> maxSize = 3145728; // sets the attachment upload size.
$ Upload-> exts = array ('jpg ', 'gif', 'png', 'jpeg '); // you can specify the attachment upload type.
$ Upload-> rootPath = './Uploads/'; // you can specify the root directory for uploading attachments.
$ Upload-> savePath = ''; // sets the attachment upload (sub) directory.
// Upload a file
$info = $upload->upload();
If (! $ Info) {// upload error message
$this->error($upload->getError());
} Else {// upload successful
$ This-> success ('upload successful! ');
}
}
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.finfo
Module 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:
$config = array(
'maxSize'=>3145728,
'rootPath'=>'./Uploads/',
'savePath'=>'',
'saveName'=> array('uniqid',''),
'exts'=> array('jpg','gif','png','jpeg'),
'autoSub'=>true,
'subName'=> array('date','Ymd'),
);
$ 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:
$ Upload = new \ Think \ Upload (); // instantiate the upload class
$upload->maxSize =3145728;
$upload->rootPath ='./Uploads/';
$upload->savePath ='';
$upload->saveName = array('uniqid','');
$upload->exts = array('jpg','gif','png','jpeg');
$upload->autoSub =true;
$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\Upload
Class 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.
$ Upload = new \ Think \ Upload (); // instantiate the upload class
$ Upload-> maxSize = 3145728; // sets the attachment upload size.
$ Upload-> exts = array ('jpg ', 'gif', 'png', 'jpeg '); // you can specify the attachment upload type.
$ Upload-> rootPath = './Uploads/'; // you can specify the root directory for uploading attachments.
$ Upload-> savePath = ''; // sets the attachment upload (sub) directory.
// Upload a file
$info = $upload->upload();
If (! $ Info) {// upload error message
$this->error($upload->getError());
} Else {// the uploaded file is successfully obtained.
foreach($info as $file){
echo $file['savepath'].$file['savename'];
}
}
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:
$model = M('Photo');
// Obtain the information of the successfully uploaded file
$info = $upload->upload();
// Save the current data object
$data['photo']= $info[0]['savename'];
$data['create_time']= NOW_TIME;
$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:
publicfunction upload(){
$ Upload = new \ Think \ Upload (); // instantiate the upload class
$ Upload-> maxSize = 3145728; // sets the attachment upload size.
$ Upload-> exts = array ('jpg ', 'gif', 'png', 'jpeg '); // you can specify the attachment upload type.
$ Upload-> rootPath = './Uploads/'; // you can specify the root directory for uploading attachments.
// Upload a single object
$info = $upload->uploadOne($_FILES['photo1']);
If (! $ Info) {// upload error message
$this->error($upload->getError());
} Else {// the uploaded file is successfully obtained.
echo $info['savepath'].$info['savename'];
}
}
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:
// Use the timestamp name
$upload->saveName ='time';
// Use the GUID sequence name
$upload->saveName ='com_create_guid';
You can also use user-defined functions.
// Use the custom function name
$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:
// Use the date function to generate a naming rule and input the Y-m-d parameter.
$upload->saveName = array('date','Y-m-d');
// Use an array if multiple parameters need to be input.
$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:
$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.
$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:
$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 setautoSub
AndsubName
Parameters, for example:
// Enable subdirectory saving and use the date (Format: Ymd) as the subdirectory
$upload->autoSub =true;
$upload->subName = array('date','Ymd');
You can use a custom function to save data. For example:
// Enable sub-directory saving and call the custom function get_user_id to generate sub-Directories
$upload->autoSub =true;
$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:
'FILE_UPLOAD_TYPE'=>'Ftp',
'UPLOAD_TYPE_CONFIG'=> array(
'Host' => '192. 168.1.200 ', // server
'Port' => 21, // port
'Timeout' => 90, // timeout
'Username' => 'ftp _ user', // user Name
'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:
$config = array(
'maxSize'=3145728,
'rootPath'='./Uploads/',
'savePath'='',
'saveName'= array('uniqid',''),
'exts'= array('jpg','gif','png','jpeg'),
'autoSub'=true,
'subName'= array('date','Ymd'),
);
$ftpConfig = array(
'Host' => '192. 168.1.200 ', // server
'Port' => 21, // port
'Timeout' => 90, // timeout
'Username' => 'ftp _ user', // user Name
'Password' => 'ftp _ pwd', // password );
-
$ Upload = new \ Think \ Upload ($ config, 'ftp ', $ ftpConfig); // instantiate the upload class