CI(2.2) 配置 jquery的上传插件Uploadify(v3.2) 上传文件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了CI(2.2) 配置 jquery的上传插件Uploadify(v3.2) 上传文件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含11867字,纯文字阅读大概需要17分钟。
内容图文
1、下载uploadify, 我的是v3.2
2、模板页面引入:
<base href=‘{base_url()}‘ /> <script type="text/javascript" src="/public/admin/js/jquery.js"></script> <script type="text/javascript" src="/public/js/ajaxfileupload.js"></script> <script type="text/javascript" src="/public/js/uploadify/jquery.uploadify.min.js"></script> <link rel="stylesheet" type="text/css" href="/public/js/uploadify/uploadify.css" />
3、模板页面使用:
< tr > < td style ="text-align:center;padding-top:10px;" >< span class ="red" > * </span>上传并扫描应用:</td><td><input id="uploadApk" name="uploaApk" type="file"/><span id="upload_note"> {if $edit}<font color=‘red‘>已上传应用“{$apply[‘name‘]}” </font>{else}<font color=‘red‘>建议应用包100M以内</font>{/if} </span></td></tr>
4、js code:
<script>
window.apk_uploading_flag = 0; $(function() { var seid = ‘{$seid}‘ ; var type = ‘‘ ; var vid = "{$apply[‘vid‘]}"; $("#uploadApk").uploadify({ height : 30, swf : ‘/public/js/uploadify/uploadify.swf‘,//Uploadify 自带的flash uploader : ‘/admin/ajaxSelfUpload‘,//ajax提交页面 width : 120, buttonText : ‘上传应用‘, method : ‘post‘, debug : false, fileTypeExts : ‘*.apk‘, sizeLimit : 512000, fileObjName : ‘uploadApk‘, progressData : ‘speed‘ , formData : { ‘session_tmp‘: ‘‘ }, onUploadStart:function(){ window.apk_uploading_flag = 1; $("#uploadApk").uploadify(‘settings‘,‘formData‘,{ ‘session‘: seid}); }, onUploadComplete:function(){ window.apk_uploading_flag = 0; }, onUploadSuccess:function(file,data,response){ var data = JSON.parse(data) if(data.status){ $("#upload_note font").html(‘应用上传并扫描成功‘); }else{ $("#upload_note font").html(data.info); } } });
</script>
5、controller中代码
1、seid取值
$this->assign(‘seid‘, $this->input->cookie($this->config->item(‘cookie_prefix‘) . $this->config->item(‘sess_cookie_name‘)));
2、上传函数
/* * * 上传应用本身并扫描 */ public function ajaxSelfUpload() { $strError = ‘‘; $this->load->library("MyUpload");//上传类 $tmpFile = $_FILES[‘uploadApk‘]; $editId = $this->input->get(‘vid‘); $apkSize = $tmpFile[‘size‘]; $apkName = $tmpFile[‘name‘]; //判断文件格式、大小、判断包名是否已经存在 //通过aapt获得apk的所有信息,将上传的apk解压到临时目录$upload = new MyUpload($tmpFile); $upload->setFileExt(array(‘apk‘)); $upload->setMaxsize(1024 * 1024 * 500); //reset upload path with category $uploadApkDir = $this->getSelfUploadDir(); $upload->setUploadPath($uploadApkDir); if (!$upload->isAllowedTypes()) { $strError = ‘上传文件不是有效的apk文件‘; } elseif ($upload->isBigerThanMaxSize()) { $strError = ‘上传文件最大不能超过 ‘ . intval($upload->getMaxsize() / 1024) . ‘KB‘; } //保证上传的生成的文件唯一而不覆盖其他文件if (empty($strError) and $upload->upload(false, FALSE)) { $uploadApkFilePath = $upload->getUplodedFilePath(); $this->load->library(‘ParseApkInfo‘); $ParseApkInfo = new ParseApkInfo($uploadApkFilePath); $apkInfoArray = $ParseApkInfo->getApkMoreInfo(); if (!$ParseApkInfo->getErrorMessage() && $apkInfoArray) { $apkInfoArray[‘icon‘] = $ParseApkInfo->createApkIcon(‘/auto/apply/img/‘, ‘/auto/apply/img/‘); if (!$ParseApkInfo->getErrorMessage()) { $apkInfoArray[‘size‘] = $apkSize; $apkInfoArray[‘size_mb‘] = round($apkSize / 1024 / 1024, 2); $apkInfoArray[‘apk‘] = ToolsHelper::getFileAccessUrl($uploadApkFilePath); $apkInfoArray[‘icon_url‘] = ToolsHelper::getFileAccessUrl($apkInfoArray[‘icon‘]); ajaxReturn("OK", true, $apkInfoArray); } } ajaxReturn($ParseApkInfo->getErrorMessage(), false); } else { ajaxReturn($strError, false); } } /** * 应用apk包存放目录 * @return string */privatefunction getSelfUploadDir() { return ToolsHelper::getSelfUploadDir(); }
基本配置完成,但是由于是在管理后台上传文件,所以flash 没有上传session需要手工配置下CI(uploadify配置本身简单,就是再配置后台登录上传的session的时候我花费了很长 时间所以跟大家分享出来)
修改system\libraries下面的Session.php文件:
修改sess_read函数:修改了2处
1 function sess_read() 2 { 3 // Fetch the cookie 4 //$session = $this->CI->input->cookie($this->sess_cookie_name); 5 //为了能够在各大浏览器支持falsh上传文件,对140行处进行以下修改 (修改第一处) 6 if($this->CI->input->post(‘session_tmp‘)){ 7$session = $this->CI->input->post(‘session_tmp‘); 8 }else{ 9$session = $this->CI->input->cookie($this->sess_cookie_name); 10 } 11//修改结束 12 13 // No cookie? Goodbye cruel world!... 14if ($session === FALSE) 15 { 16 log_message(‘debug‘, ‘A session cookie was not found.‘); 17returnFALSE; 18 } 19 20// HMAC authentication 21$len = strlen($session) - 40; 22 23if ($len <= 0) 24 { 25 log_message(‘error‘, ‘Session: The session cookie was not signed.‘); 26returnFALSE; 27 } 28 29// Check cookie authentication 30$hmac = substr($session, $len); 31$session = substr($session, 0, $len); 32 33// Time-attack-safe comparison 34$hmac_check = hash_hmac(‘sha1‘, $session, $this->encryption_key); 35$diff = 0; 36 37for ($i = 0; $i < 40; $i++) 38 { 39$xor = ord($hmac[$i]) ^ ord($hmac_check[$i]); 40$diff |= $xor; 41 } 42 43if ($diff !== 0) 44 { 45 log_message(‘error‘, ‘Session: HMAC mismatch. The session cookie data did not match what was expected.‘); 46$this->sess_destroy(); 47returnFALSE; 48 } 49 50// Decrypt the cookie data 51if ($this->sess_encrypt_cookie == TRUE) 52 { 53$session = $this->CI->encrypt->decode($session); 54 } 55 56// Unserialize the session array 57$session = $this->_unserialize($session); 58 59// Is the session data we unserialized an array with the correct format? 60if ( ! is_array($session) OR ! isset($session[‘session_id‘]) OR ! isset($session[‘ip_address‘]) OR ! isset($session[‘user_agent‘]) OR ! isset($session[‘last_activity‘])) 61 { 62$this->sess_destroy(); 63returnFALSE; 64 } 65 66// Is the session current? 67if (($session[‘last_activity‘] + $this->sess_expiration) < $this->now) 68 { 69$this->sess_destroy(); 70returnFALSE; 71 } 72 73// Does the IP Match? 74if ($this->sess_match_ip == TRUE AND $session[‘ip_address‘] != $this->CI->input->ip_address()) 75 { 76$this->sess_destroy(); 77returnFALSE; 78 } 79//为了能够在各大浏览器支持falsh上传文件,对199行处进行以下修改 (修改第二处) 80if (stristr($this->CI->input->user_agent(),‘shockwave‘)) 81 { 82$this->sess_match_useragent = FALSE; 83 } 84//修改结束 85 86 // Does the User Agent Match? 87if ($this->sess_match_useragent == TRUE AND trim($session[‘user_agent‘]) != trim(substr($this->CI->input->user_agent(), 0, 120))) 88 { 89$this->sess_destroy(); 90returnFALSE; 91 } 92 93// Is there a corresponding session in the DB? 94if ($this->sess_use_database === TRUE) 95 { 96$this->CI->db->where(‘session_id‘, $session[‘session_id‘]); 97 98if ($this->sess_match_ip == TRUE) 99 { 100$this->CI->db->where(‘ip_address‘, $session[‘ip_address‘]); 101 } 102103if ($this->sess_match_useragent == TRUE) 104 { 105$this->CI->db->where(‘user_agent‘, $session[‘user_agent‘]); 106 } 107108$query = $this->CI->db->get($this->sess_table_name); 109110// No result? Kill it!111if ($query->num_rows() == 0) 112 { 113$this->sess_destroy(); 114returnFALSE; 115 } 116117// Is there custom data? If so, add it to the main session array118$row = $query->row(); 119if (isset($row->user_data) AND $row->user_data != ‘‘) 120 { 121$custom_data = $this->_unserialize($row->user_data); 122123if (is_array($custom_data)) 124 { 125foreach ($custom_dataas$key => $val) 126 { 127$session[$key] = $val; 128 } 129 } 130 } 131 } 132133// Session is valid!134$this->userdata = $session; 135unset($session); 136137returnTRUE; 138 }
疑问:刚开始配置完仍然上传不成功,后来排查原因,什么也没改动,然后不小心试了试就好了……所以如有问题@me
在此贴出上传类:MyUpload
application\libraries\MyUpload.php
<?php class MyUpload { private$allowedTypes = array(‘image/jpg‘,‘image/bmp‘, ‘image/jpe‘, ‘image/jpeg‘, ‘image/pjpeg‘, ‘image/x-png‘,‘image/png‘,‘image/gif‘); private$fileExt = array(‘jpg‘); private$uploadPath = ‘‘; private$maxSize = 307200;//300kpublicfunction __construct(array$file=array()) { $this->file = $file; } /** * 设置文件的上传目录,绝对地址 * @param string $uploadPath * @return null */publicfunction setUploadPath($uploadPath=UPLOAD_DIR) { $this->uploadPath = $uploadPath; } /** * 设置文件的大小,byte单位 * @param integer $maxSize * @return null */publicfunction setMaxsize($maxSize) { $this->maxSize = $maxSize; } /** * 设置允许上传的文件mime * @param array $allowedTypes 允许上传的文件类型数组 例如:array(‘image/jpg‘,‘image/bmp‘) * @return null */publicfunction setAllowedTypes(array$allowedTypes) { $this->allowedTypes = $allowedTypes; } /** * 设置允许上传的文件的后缀名 * @param array $fileExt 例如:array(‘jpg‘,‘png‘) * @return null */publicfunction setFileExt(array$fileExt) { $this->fileExt = $fileExt; } /** * 获取文件的大小 * @return integer */publicfunction getMaxsize() { return$this->maxSize; } /** * 获取允许上传的图片后缀名 * @param unknown_type $val * @param array $array * @return unknown_type */publicfunction getaAllowedExt() { return$this->allowedTypes; } /** * 检查文件大小,是否超过了文件的大小限制 * @return bool */publicfunction isBigerThanMaxSize() { return$this->file["size"] > $this->maxSize; } /** * 检查文件后缀名是否正确 * @return unknown_type */publicfunction isAllowedTypes() { // $fileExt = array(‘gif‘, ‘jpg‘, ‘jpeg‘, ‘png‘, ‘jpe‘); // $fileExt = array(‘jpg‘);$ext = $this->getFileExt(); if (in_array($ext, $this->fileExt)) { if ($this->file[‘tmp_name‘] === FALSE) { returnfalse; } } else { returnfalse; } returntrue; } /** * 验证文件的内容类型 * @return bool */publicfunction isAllowedMime() { if( in_array($this->file["type"],$this->allowedTypes) ) { returntrue; } } /** * 获取文件后缀名 * @return string|null */publicfunction getFileExt() { $x = explode(‘.‘, $this->file[‘name‘]); returnstrtolower(end($x)); } /** * 检查图片大小是否正确 * @param integer $width 被允许的宽度 * @param integer $height 被允许的高度 * @return bool */publicfunction isAllowedSize($width,$height) { //对于上传的文件类型,大小,尺寸等做验证。。此处暂时省略$fileSize = getimagesize($this->file[‘tmp_name‘]); $fileWidth = $fileSize[0]; $fileHeight = $fileSize[1]; if($fileWidth != $width or $fileHeight != $height) { returnfalse; } returntrue; } /** * 检查图片大小是否正确 只要不大于设置的最大宽高就可以 * @param integer $width 被允许的最大宽度 * @param integer $height 被允许的最大高度 * @return bool */publicfunction isAllowedMaxSize($width,$height) { $fileSize = getimagesize($this->file[‘tmp_name‘]); $fileWidth = $fileSize[0]; $fileHeight = $fileSize[1]; if($fileWidth > $width or $fileHeight > $height) { returnfalse; } returntrue; } /** * 上传图片 * @param bool $isReplace 如果存在同名图片是否覆盖 * @param bool $isNewName 是否产生新的文件名或是用上传文件自身名字 * @return bool */publicfunction upload($isReplace=true,$isNewName=true) { if($isNewName){ $filename = self::createKey().‘.‘.$this->getFileExt(); }else{ $filename = $this->file["name"]; } if (file_exists($this->uploadPath. "/" . $filename)) { if($isReplace){ @unlink($this->uploadPath. "/" . $filename); }else{ $tmpExt = ‘.‘.$this->getFileExt(); $filename = rtrim($this->file[‘name‘], $tmpExt); $filename .= "_" . date(‘ymd‘,time()).‘_‘.date(‘His‘,time()).$tmpExt; } } self::createDir($this->uploadPath); if ( ! @copy($this->file["tmp_name"], $this->uploadPath. "/" . $filename)) { if ( ! move_uploaded_file($this->file["tmp_name"], $this->uploadPath. "/" . $filename)) { returnfalse; } } $this->filePath = str_replace(UPLOAD_DIR,‘‘,$this->uploadPath. "/" . $filename); returntrue; } /** * 获取文件的真实名称 * @return string */publicfunction getRealName() { return$this->file[‘name‘]; } /** * 生成一串随机数字 * @return string */publicstaticfunction createKey() { $randpwd = ‘‘; for ($i = 0; $i < 10; $i++) { $randpwd .= mt_rand(33, 500); } returnmd5($randpwd); } /** * 返回被保存的带路径的文件名 * @return string */publicfunction getUplodedFilePath() { return @$this->filePath; } /** * 循环创建目录 * @param string $path * @return null */publicstaticfunction createDir($path){ if(!is_readable($path)){ self::createDir( dirname($path) ); if(!is_file($path)) mkdir($path,0777); } } }
原文:http://www.cnblogs.com/zhhtao/p/4309471.html
内容总结
以上是互联网集市为您收集整理的CI(2.2) 配置 jquery的上传插件Uploadify(v3.2) 上传文件全部内容,希望文章能够帮你解决CI(2.2) 配置 jquery的上传插件Uploadify(v3.2) 上传文件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。