ExtJS has packaged components to achieve file upload function is very convenient, but for many ExtJS novice does not know how to control the file upload type, such as when we just want to let users upload ' txt ' type of files, how to achieve when users upload non ' TXT ' file, give the wrong hint? The validator validator using the field component should be a convenient way to verify the file type.
In extjs4.x How to implement the password verification function in an article we have used validator to verify the password, today we borrow file upload function, for you to share the details of the use of validator. First, give the code to implement the file upload function:
The code is as follows |
Copy Code |
Ext.application ({ Name: ' Demo ', Appfolder: ' App ', Launch:function () { Ext.create (' Ext.container.Viewport ', { Margin: ' 100 0 0 200 ', items:[{ Xtype: ' Form ', Title: ' ExtJS file Upload ', width:400, HEIGHT:300, Defaults: { Margin: ' 20 0 0 30 ', }, Items: [{ Xtype: ' Filefield ', Name: ' File ', Fieldlabel: ' Upload file ', ButtonText: ' Select File ', LABELWIDTH:80, WIDTH:300, Allowblank:false, Msgtarget: ' under ', Validator:function (value) { var arr = value.split ('. '); if (arr[arr.length-1]!= ' txt ') { Return ' File not valid!!! '; }else{ return true; } } },{ Xtype: ' button ', Margin: ' 100 0 0 200 ', Text: ' OK upload ', Handler:function (b,e) { var form = B.up (). GetForm (); if (Form.isvalid ()) { Form.submit ({ URL: ' uploadfile.php ', Success:function (form, action) { Ext.MessageBox.alert (' Hint: ', action.result.msg); }, Failure:function (form, action) { Ext.MessageBox.alert (' Hint: ', action.result.msg); } }); } } }] }] }); } }); |
PHP (uploadfile.php) Background code:
code is as follows |
copy code |
<?php $file = $_files["File" ["Tmp_name"]; $file _name = $_files["File" ["name"]; $result = Move_uploaded_file ($file, "/uploads/". $file _name); $data [' success '] = $result; if ($result) { $data [' msg '] = ' upload succeeded '; echo Json_encode ($data); } else{ $data [' msg '] = ' upload failed '; echo Json_encode ($data); ?> |
Validator:
Validator is a configuration item for filefiled (All text box components basically have this configuration item, use exactly the same), The biggest difference with other configuration items is that the value of the validator is a function, as shown in the code, which has a unique parameter value (the value in the text box), and validation of the value in the function body if the file is valid to return True, The wrong way to return the error message, this verification is complete, validator use is so simple!
Note: Validation of the upload file type is not only a validator method, but using regular (configuration items: Regex) can achieve the same effect, in this special statement, MO to be limited to this one method of Lee bad, we can try a lot.