PHP之uploadify上传插件代码演示

以下是我最近在做的CI项目时候用到的uploadify上传插件的代码,其中返回值的处理我只用到了一个事件(已经足够了),有兴趣的朋友可以去官网查看更多相关事件。传送门:uploadify官网事件地址

/*客户端代码*/
<input id="file_upload" name="file_upload" type="file" multiple="true"> 
<script type="text/javascript">
    <?php $timestamp = time();?>
    $(function() {
        $('#file_upload').uploadify({
            'formData'     : {
                'timestamp' : '<?php echo $timestamp;?>',
                'token'     : '<?php echo md5('unique_salt' . $timestamp);?>'  //uploadify默认token
            },
            'buttonText':'上传文件',
            'fileTypeExts' : '*.doc;*.docx;*.pdf;',
            'swf'      : '<?php echo base_url("js/uploadify/uploadify.swf");?>',   //框架中的全局函数  相当于路径
            'uploader' : '<?php echo base_url('module/files/main/uploadify')?>',
            'onUploadSuccess' : function(file, data, response) {  
                 alert(data);
            },
        });
    });
</script>
-----------------要有华丽的分割线----------------------
/*服务器端代码*/
public function uploadify() {
    $type = $_GET['type'];  
    $targetPath = './uploads/uploadify_file';    //保存路径
    $verifyToken = md5('unique_salt' . $_POST['timestamp']);   //接收客户端token

    if (!empty($_FILES) && $_POST['token'] == $verifyToken) {   //验证token
        $tempFile = $_FILES['Filedata']['tmp_name'];
        if (!file_exists($targetPath)) {     //文件夹不存在  创建之
            @mkdir($targetPath);
            chmod($targetPath, 0777);   //0777读写权限
        }
        $file_name = $_FILES['Filedata']['name'];
        $hz = explode(".",$_FILES['Filedata']['name']);
        $targetFile = rtrim($targetPath,'/') . '/' . md5(time()).".".$hz[1];
        // Validate the file type
        $fileTypes = array('doc','docx','pdf'); // File extensions
        $fileParts = pathinfo($_FILES['Filedata']['name']);
        if (in_array($fileParts['extension'],$fileTypes)) {    //后端验证文件类型  虽然前端有验证 但是遵循不相信用户的输入
            if(move_uploaded_file($tempFile,$targetFile)){
                $file_message = array(
                    'file_name'=>$file_name,
                    'file_creat_time'=>time(),
                    'file_url'=> $targetFile,
                    'file_type'=>$type
                    );
                $res = $this->files_Model->insert($file_message);    保存到数据库
                if (!$res) {
                    echo '文件'.$file_message['name'].'保存失败'; 
                    return FALSE;
                }else{
                    echo '上传成功';
                    return TRUE;
                }
            }else{
                echo '啊哦!文件移动失败了,请检查文件路径';
                return FALSE;
            }
        } else {
            echo '文件类型不匹配哈!';
            return FALSE;
        }
    }
}

以上。

添加新评论