码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2015-03-02 20:45:18      阅读:1094      评论:0      收藏:0      [点我收藏+]

标签:

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处

技术分享
  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!...
 14         if ($session === FALSE)
 15         {
 16             log_message(‘debug‘, ‘A session cookie was not found.‘);
 17             return FALSE;
 18         }
 19 
 20         // HMAC authentication
 21         $len = strlen($session) - 40;
 22 
 23         if ($len <= 0)
 24         {
 25             log_message(‘error‘, ‘Session: The session cookie was not signed.‘);
 26             return FALSE;
 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 
 37         for ($i = 0; $i < 40; $i++)
 38         {
 39             $xor = ord($hmac[$i]) ^ ord($hmac_check[$i]);
 40             $diff |= $xor;
 41         }
 42 
 43         if ($diff !== 0)
 44         {
 45             log_message(‘error‘, ‘Session: HMAC mismatch. The session cookie data did not match what was expected.‘);
 46             $this->sess_destroy();
 47             return FALSE;
 48         }
 49 
 50         // Decrypt the cookie data
 51         if ($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?
 60         if ( ! 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();
 63             return FALSE;
 64         }
 65 
 66         // Is the session current?
 67         if (($session[‘last_activity‘] + $this->sess_expiration) < $this->now)
 68         {
 69             $this->sess_destroy();
 70             return FALSE;
 71         }
 72 
 73         // Does the IP Match?
 74         if ($this->sess_match_ip == TRUE AND $session[‘ip_address‘] != $this->CI->input->ip_address())
 75         {
 76             $this->sess_destroy();
 77             return FALSE;
 78         }
 79         //为了能够在各大浏览器支持falsh上传文件,对199行处进行以下修改   (修改第二处)
 80          if (stristr($this->CI->input->user_agent(),‘shockwave‘))
 81          {
 82             $this->sess_match_useragent = FALSE;
 83          }
 84          //修改结束
 85 
 86         // Does the User Agent Match?
 87         if ($this->sess_match_useragent == TRUE AND trim($session[‘user_agent‘]) != trim(substr($this->CI->input->user_agent(), 0, 120)))
 88         {
 89             $this->sess_destroy();
 90             return FALSE;
 91         }
 92                 
 93         // Is there a corresponding session in the DB?
 94         if ($this->sess_use_database === TRUE)
 95         {
 96             $this->CI->db->where(‘session_id‘, $session[‘session_id‘]);
 97 
 98             if ($this->sess_match_ip == TRUE)
 99             {
100                 $this->CI->db->where(‘ip_address‘, $session[‘ip_address‘]);
101             }
102 
103             if ($this->sess_match_useragent == TRUE)
104             {
105                 $this->CI->db->where(‘user_agent‘, $session[‘user_agent‘]);
106             }
107 
108             $query = $this->CI->db->get($this->sess_table_name);
109 
110             // No result?  Kill it!
111             if ($query->num_rows() == 0)
112             {
113                 $this->sess_destroy();
114                 return FALSE;
115             }
116 
117             // Is there custom data?  If so, add it to the main session array
118             $row = $query->row();
119             if (isset($row->user_data) AND $row->user_data != ‘‘)
120             {
121                 $custom_data = $this->_unserialize($row->user_data);
122 
123                 if (is_array($custom_data))
124                 {
125                     foreach ($custom_data as $key => $val)
126                     {
127                         $session[$key] = $val;
128                     }
129                 }
130             }
131         }
132 
133         // Session is valid!
134         $this->userdata = $session;
135         unset($session);
136 
137         return TRUE;
138     }
View Code

 

疑问:刚开始配置完仍然上传不成功,后来排查原因,什么也没改动,然后不小心试了试就好了……所以如有问题@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);
        }
    }


}
View Code

 

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

标签:

原文地址:http://www.cnblogs.com/zhhtao/p/4309471.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!