AjaxFileUploader+thinkphp实现无刷新文件上传的示例代码
分类:PHP_Python| 发布:kuabaobao| 查看:264 | 发表时间:2015/6/2
首先,AjaxFileUploader插件是一个基于jquery的插件,我们可以使用AjaxFileUploader插件来实现文件异步上传功能了,使用这款插件上传文件不要担心兼容性的问题,它的兼容性可以说兼容所有主流浏览器,下面来给大家介绍一个AjaxFileUploader+thinkphp实现文件上传的实例。
ThinkPHP框架下用AjaxFileUploader插件实现ajax文件上传,支持多种文件格式,页面无刷新上传。
在Lib/Action/目录下创建upAction.class.php文件,代码如下:
代码如下:
02 | class upAction extends BaseAction{ |
03 | public function index(){ |
12 | public function upLoadFile(){ |
15 | $fileElementName = 'fileToUpload' ; |
16 | if (! empty ( $_FILES [ $fileElementName ][ 'error' ])){ |
17 | switch ( $_FILES [ $fileElementName ][ 'error' ]){ |
19 | $error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini' ; |
22 | $error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form' ; |
25 | $error = 'The uploaded file was only partially uploaded' ; |
28 | $error = 'No file was uploaded.' ; |
32 | $error = 'Missing a temporary folder' ; |
35 | $error = 'Failed to write file to disk' ; |
38 | $error = 'File upload stopped by extension' ; |
42 | $error = 'No error code avaiable' ; |
44 | } elseif ( empty ( $_FILES [ 'fileToUpload' ][ 'tmp_name' ]) || $_FILES [ 'fileToUpload' ][ 'tmp_name' ] == 'none' ){ |
45 | $error = 'No file was uploaded..' ; |
49 | $error = 'Up file fail' ; |
51 | $msg = $re [ 'savename' ]; |
52 | $path = '/upload/bizcoop/' . $msg ; |
55 | echo json_encode( array ( 'error' => $error , 'msg' => $msg , 'path' => $path , 'size' => $size )); exit ; |
58 | private function up(){ |
59 | import( '@.Org.UploadFile' ); |
60 | $upload = new UploadFile(); |
62 | $upload ->maxSize= '-1' ; |
63 | $upload ->savePath= ICTSPACE_DIST_ROOT_PATH. '/www/upload/bizcoop/' ; |
64 | $upload ->saveRule=uniqid; |
65 | $upload ->uploadReplace=true; |
66 | $upload ->allowExts= array ( 'jpg' , 'jpeg' , 'png' , 'gif' ); |
67 | if ( $upload ->upload()){ |
68 | $info = $upload ->getUploadFileInfo(); |
在/Tpl/default/Up/目录下创建index.tpl文件,代码如下:
代码如下:
02 | < h1 >Ajax File Upload Demo</ h1 > |
03 | < img id = "loading" style = "display: none;" alt = "" src = "__APP____PUBLIC__/style/img/loading.gif" /> |
05 | < form action = "" enctype = "multipart/form-data" method = "POST" name = "form" > |
06 | < table class = "tableForm" cellspacing = "0" cellpadding = "0" > |
14 | < td >< input class = "input" id = "fileToUpload" type = "file" name = "fileToUpload" size = "45" /></ td > |
17 | < td >< button class = "button" id = "buttonUpload" onclick = "return ajaxFileUpload();" >Upload</ button ></ td > |
22 | < td >< span >已上传的附件:</ span ></ td > |
在/Lib/Org/目录下放入ThinkPHP文件上传类就可以了,有一些插件我们需要到官方下载。