CI(2.2) 配置 jquery的上传插件Uploadify(v3.2) 上传文件

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']}”&nbsp; </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
*/
private function getSelfUploadDir() {
return ToolsHelper::getSelfUploadDir();
}

基本配置完成,但是由于是在管理后台上传文件,所以flash 没有上传session需要手工配置下CI(uploadify配置本身简单,就是再配置后台登录上传的session的时候我花费了很长 时间所以跟大家分享出来)

修改system\libraries下面的Session.php文件:

修改sess_read函数:修改了2处

 function sess_read()
{
// Fetch the cookie
//$session = $this->CI->input->cookie($this->sess_cookie_name);
//为了能够在各大浏览器支持falsh上传文件,对140行处进行以下修改 (修改第一处)
if($this->CI->input->post('session_tmp')){
$session = $this->CI->input->post('session_tmp');
}else{
$session = $this->CI->input->cookie($this->sess_cookie_name);
}
//修改结束 // No cookie? Goodbye cruel world!...
if ($session === FALSE)
{
log_message('debug', 'A session cookie was not found.');
return FALSE;
} // HMAC authentication
$len = strlen($session) - 40; if ($len <= 0)
{
log_message('error', 'Session: The session cookie was not signed.');
return FALSE;
} // Check cookie authentication
$hmac = substr($session, $len);
$session = substr($session, 0, $len); // Time-attack-safe comparison
$hmac_check = hash_hmac('sha1', $session, $this->encryption_key);
$diff = 0; for ($i = 0; $i < 40; $i++)
{
$xor = ord($hmac[$i]) ^ ord($hmac_check[$i]);
$diff |= $xor;
} if ($diff !== 0)
{
log_message('error', 'Session: HMAC mismatch. The session cookie data did not match what was expected.');
$this->sess_destroy();
return FALSE;
} // Decrypt the cookie data
if ($this->sess_encrypt_cookie == TRUE)
{
$session = $this->CI->encrypt->decode($session);
} // Unserialize the session array
$session = $this->_unserialize($session); // Is the session data we unserialized an array with the correct format?
if ( ! is_array($session) OR ! isset($session['session_id']) OR ! isset($session['ip_address']) OR ! isset($session['user_agent']) OR ! isset($session['last_activity']))
{
$this->sess_destroy();
return FALSE;
} // Is the session current?
if (($session['last_activity'] + $this->sess_expiration) < $this->now)
{
$this->sess_destroy();
return FALSE;
} // Does the IP Match?
if ($this->sess_match_ip == TRUE AND $session['ip_address'] != $this->CI->input->ip_address())
{
$this->sess_destroy();
return FALSE;
}
//为了能够在各大浏览器支持falsh上传文件,对199行处进行以下修改 (修改第二处)
if (stristr($this->CI->input->user_agent(),'shockwave'))
{
$this->sess_match_useragent = FALSE;
}
//修改结束 // Does the User Agent Match?
if ($this->sess_match_useragent == TRUE AND trim($session['user_agent']) != trim(substr($this->CI->input->user_agent(), 0, 120)))
{
$this->sess_destroy();
return FALSE;
} // Is there a corresponding session in the DB?
if ($this->sess_use_database === TRUE)
{
$this->CI->db->where('session_id', $session['session_id']); if ($this->sess_match_ip == TRUE)
{
$this->CI->db->where('ip_address', $session['ip_address']);
} if ($this->sess_match_useragent == TRUE)
{
$this->CI->db->where('user_agent', $session['user_agent']);
} $query = $this->CI->db->get($this->sess_table_name); // No result? Kill it!
if ($query->num_rows() == 0)
{
$this->sess_destroy();
return FALSE;
} // Is there custom data? If so, add it to the main session array
$row = $query->row();
if (isset($row->user_data) AND $row->user_data != '')
{
$custom_data = $this->_unserialize($row->user_data); if (is_array($custom_data))
{
foreach ($custom_data as $key => $val)
{
$session[$key] = $val;
}
}
}
} // Session is valid!
$this->userdata = $session;
unset($session); return TRUE;
}

疑问:刚开始配置完仍然上传不成功,后来排查原因,什么也没改动,然后不小心试了试就好了……所以如有问题@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;//300k public function __construct(array $file=array())
{
$this->file = $file;
} /**
* 设置文件的上传目录,绝对地址
* @param string $uploadPath
* @return null
*/
public function setUploadPath($uploadPath=UPLOAD_DIR)
{
$this->uploadPath = $uploadPath;
} /**
* 设置文件的大小,byte单位
* @param integer $maxSize
* @return null
*/
public function setMaxsize($maxSize)
{
$this->maxSize = $maxSize;
} /**
* 设置允许上传的文件mime
* @param array $allowedTypes 允许上传的文件类型数组 例如:array('image/jpg','image/bmp')
* @return null
*/
public function setAllowedTypes(array $allowedTypes)
{
$this->allowedTypes = $allowedTypes;
} /**
* 设置允许上传的文件的后缀名
* @param array $fileExt 例如:array('jpg','png')
* @return null
*/
public function setFileExt(array $fileExt)
{
$this->fileExt = $fileExt;
} /**
* 获取文件的大小
* @return integer
*/
public function getMaxsize()
{
return $this->maxSize;
} /**
* 获取允许上传的图片后缀名
* @param unknown_type $val
* @param array $array
* @return unknown_type
*/
public function getaAllowedExt()
{
return $this->allowedTypes;
} /**
* 检查文件大小,是否超过了文件的大小限制
* @return bool
*/
public function isBigerThanMaxSize()
{
return $this->file["size"] > $this->maxSize;
} /**
* 检查文件后缀名是否正确
* @return unknown_type
*/
public function 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)
{
return false;
} }
else
{
return false;
} return true;
} /**
* 验证文件的内容类型
* @return bool
*/
public function isAllowedMime()
{
if( in_array($this->file["type"],$this->allowedTypes) )
{
return true;
}
} /**
* 获取文件后缀名
* @return string|null
*/
public function getFileExt()
{
$x = explode('.', $this->file['name']);
return strtolower(end($x));
} /**
* 检查图片大小是否正确
* @param integer $width 被允许的宽度
* @param integer $height 被允许的高度
* @return bool
*/
public function isAllowedSize($width,$height)
{
//对于上传的文件类型,大小,尺寸等做验证。。此处暂时省略
$fileSize = getimagesize($this->file['tmp_name']);
$fileWidth = $fileSize[0];
$fileHeight = $fileSize[1];
if($fileWidth != $width or $fileHeight != $height)
{
return false;
}
return true;
}
/**
* 检查图片大小是否正确 只要不大于设置的最大宽高就可以
* @param integer $width 被允许的最大宽度
* @param integer $height 被允许的最大高度
* @return bool
*/
public function isAllowedMaxSize($width,$height)
{
$fileSize = getimagesize($this->file['tmp_name']);
$fileWidth = $fileSize[0];
$fileHeight = $fileSize[1];
if($fileWidth > $width or $fileHeight > $height)
{
return false;
}
return true;
} /**
* 上传图片
* @param bool $isReplace 如果存在同名图片是否覆盖
* @param bool $isNewName 是否产生新的文件名或是用上传文件自身名字
* @return bool
*/
public function 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))
{ return false;
} }
$this->filePath = str_replace(UPLOAD_DIR,'',$this->uploadPath. "/" . $filename);
return true;
} /**
* 获取文件的真实名称
* @return string
*/
public function getRealName()
{
return $this->file['name'];
} /**
* 生成一串随机数字
* @return string
*/
public static function createKey()
{
$randpwd = '';
for ($i = 0; $i < 10; $i++)
{
$randpwd .= mt_rand(33, 500);
} return md5($randpwd);
} /**
* 返回被保存的带路径的文件名
* @return string
*/
public function getUplodedFilePath()
{
return @$this->filePath;
} /**
* 循环创建目录
* @param string $path
* @return null
*/
public static function createDir($path){
if(!is_readable($path)){
self::createDir( dirname($path) );
if(!is_file($path)) mkdir($path,0777);
}
} }
上一篇:Windows下CVSNT安装配置


下一篇:终极锁实战:单JVM锁+分布式锁