Home  >  Article  >  Backend Development  >  Introduction to the use of swfupload in phpcms module development_PHP tutorial

Introduction to the use of swfupload in phpcms module development_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:11:051003browse

After formally contacting phpcms module development, I developed several functional modules. Among them, I encountered the problem of batch uploading of images. So I started to explore the usage of swfupload in phpcms.

You can directly specify the image group in the content type that comes with phpcms. However, this image group function is not what I want to use. I need to upload an entire static html file. Need

Able to find a way to upload the entire folder. And be able to keep the original file name.

The purpose is summarized as follows:

1, Do not change the file and directory structure of the system.

2, realize the function of uploading multiple attachments.

3, you can get the folder name after uploading.

phpcms has its own attachment upload function. I want to use the swfupload function, and this function is integrated into the attachment upload function of phpcms. Then what I have to do is to extract it and modify it.

The first step is to study how to call this.

First, open firebug in the firefox browser and open the network panel. Find the button called up by swfupload in phpcm. See what connection the system is requesting.

Copy code The code is as follows:

?m=attachment&c=attachments&a=swfupload&args=10,,1&module=&catid=&authkey=b756a93dea2e627293e88fa9d62af709&pc_hash=iXFbo1

We captured A series of such requests. The swfupload method in the attachments controller of the attachment module is called.

Let’s find this method in this controller in this module.

Inside phpcms/modoules/attachemet/attachemts.php

Open it and take a look, the code is as follows

Copy the codeThe code is as follows:

public function swfupload (){
$grouplist = getcache('grouplist','member');
if(isset($_POST['dosubmit'])){
//We will not look at the contents of if for now Because this is the processing after uploading. We must first find how to introduce SWFUPLOAD.
} Else {
IF ($ This-& GT; isadmin == 0 &&! $ GROUPLIST ]['allowattachment']) showmessage (L('att_no_permission')); /Get the key
If(upload_key($args) != $authkey) showmessage(L('attachment_parameter_error'));//Verify the key
extract(getswfinit($_GET['args'])) ;//Split parameters
$siteid = $this->get_siteid();//Get website id
$site_setting = get_site_setting($siteid);//Get website settings
$file_size_limit = sizecount ($site_setting['upload_maxsize']*1024);//Allow upload size
                                                                                           $att_not_used =               get_cookie('att_json');                                                                      ;| ';//Otherwise the tag is hidden
$att = $this->att_not_used();//Get the temporary unprocessed file list
include $this->admin_tpl('swfupload');//This place That’s the key. Loading this template.
}
}


We will not care about the previous part, it is about uploading. I started with else. First, I verified whether attachment uploading is allowed

Then get the parameter args of swfupload from $_GET, and then verify the key. If the key passes, parse the args. Get the website id, get the website settings, and get the size of the attachment allowed to be uploaded. Get it from the cookie List of unused attachments.

Set various displays in the template. The last and most critical thing is that it uses the swfupload template. That means I need to find this template and see how swfupload is introduced.

The template is here: phpcms/modules/attachment/templates/swfupload.tpl.php

Open the template file. A bunch of files are introduced in the template file:

Copy the code The code is as follows:

< ?php $show_header = $show_validator = $show_scroll = 1; include $this->admin_tpl('header', 'attachment');?>





First of all, the header file is introduced. I will take a look at it. There is jquery or something. It is a necessary file. So we will also introduce this header when we need to use it later.

After that is the style file of swfupload and the necessary JS. Here a system function initupload is called. What does this function do?

Don’t underestimate this line. The entire swfupload configuration is here.

Let’s look for this function.

Found traces of it in phpcms/modules/attachment/functions/golable.func.php. The code is as follows. The main function of this function is to configure the swfupload plug-in.

Copy the code The code is as follows:

/* flash上传初始化
     * 初始化swfupload上传中需要的参数
     * @param $module 模块名称
     * @param $catid 栏目id
     * @param $args 传递参数
     * @param $userid 用户id
     * @param $groupid 用户组id
     * @param $isadmin 是否为管理员模式
     */
    function initupload($module, $catid,$args, $userid, $groupid = '8', $isadmin = '0'){
        $grouplist = getcache('grouplist','member');
        if($isadmin==0 && !$grouplist[$groupid]['allowattachment']) return false;
        extract(getswfinit($args));
        $siteid = param::get_cookie('siteid');
        $site_setting = get_site_setting($siteid);
        $file_size_limit = $site_setting['upload_maxsize'];
        $sess_id = SYS_TIME;
        $swf_auth_key = md5(pc_base::load_config('system','auth_key').$sess_id);
        $init =  'var swfu = \'\';
        $(document).ready(function(){
        swfu = new SWFUpload({
            flash_url:"'.JS_PATH.'swfupload/swfupload.swf?"+Math.random(),
            upload_url:"'.APP_PATH.'index.php?m=attachment&c=attachments&a=swfupload&dosubmit=1",
            file_post_name : "Filedata",
            post_params:{"SWFUPLOADSESSID":"'.$sess_id.'","module":"'.$module.'","catid":"'.$_GET['catid'].'","userid":"'.$userid.'","siteid":"'.$siteid.'","dosubmit":"1","thumb_width":"'.$thumb_width.'","thumb_height":"'.$thumb_height.'","watermark_enable":"'.$watermark_enable.'","filetype_post":"'.$file_types_post.'","swf_auth_key":"'.$swf_auth_key.'","isadmin":"'.$isadmin.'","groupid":"'.$groupid.'"},
            file_size_limit:"'.$file_size_limit.'",
            file_types:"'.$file_types.'",
            file_types_description:"All Files",
            file_upload_limit:"'.$file_upload_limit.'",
            custom_settings : {progressTarget : "fsUploadProgress",cancelButtonId : "btnCancel"},

            button_image_url: "",
            button_width: 75,
            button_height: 28,
            button_placeholder_id: "buttonPlaceHolder",
            button_text_style: "",
            button_text_top_padding: 3,
            button_text_left_padding: 12,
            button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
            button_cursor: SWFUpload.CURSOR.HAND,

file_dialog_start_handler: fileDialogStart,
file_queued_handler: fileQueued,
file_queue_error_handler:fileQueueError,
file_dialog_complete_hand ler:fileDialogComplete,
                                                                                   upload_progress_handler: uploadProgress, 🎜>           upload_complete_handler:uploadComplete
                                                                                                                                                                wfupload.tpl. php

This template uses a js to control

  • to be displayed in the form of a tab. We can use firebug to find the id of the tab with the swfupload button we want to find

    That id is tab_swf_1
    < div id="div_swf_1" class="content pad-10 ">
                                                                                ; " value="" onClick="swfu.startUpload();" />
                                   
    ,

  •                                               ">

                             
    onclick ="change_params()">

                                                                                   >                                                                                              ul class="attachment-list" id="fsUploadProgress">


    Here we see that there is a span whose id is buttonPlaceHolder and there is such a line button_placeholder_id: "buttonPlaceHolder" in the configuration file. It is obvious. When the page is loaded, the element with the id buttonPlaceHolder will be replaced by JS and uploaded by swfupload. Controls.

    In the next step, we need to trigger the swf upload method after clicking on the file

    You will find the following code in the code. The swfu.startUpload() method is called here. This method is defined in swfupload.js. We don’t need to pay attention to it.

    Copy Code The code is as follows:



    So far. We have found how to use the upload control of swfupload

    How to call this thing in my program

    First of all, we need to introduce these necessary files into the template that appears in this control

    Copy the code The code is as follows:







    The code is as shown above.

    Then write such a tag in our template where you want to place swfupload

    Copy the code The code is as follows:


    Copy the code The code is as follows:

    upload_url :"'.APP_PATH.'index.php?m=attachment&c=attachments&a=swfupload&dosubmit=1",

    This obviously reveals that we uploaded the file to the attachments controller in the attachment module swfupload method to handle

    This place is the stuff inside the if that I didn’t pay attention to before.

    Take it out and take a look

    Copy the code The code is as follows:

    if( $_POST['swf_auth_key'] != md5(pc_base::load_config('system','auth_key').$_POST['SWFUPLOADSESSID']) || ($_POST['isadmin']==0 && !$grouplist[$_POST['groupid']]['allowattachment'])) exit();
                pc_base::load_sys_class('attachment','',0);
                $attachment = new attachment($_POST['module'],$_POST['catid'],$_POST['siteid']);
                $attachment->set_userid($_POST['userid']);
                $aids = $attachment->upload('Filedata',$_POST['filetype_post'],'','',array($_POST['thumb_width'],$_POST['thumb_height']),$_POST['watermark_enable']);
                if($aids[0]) {
                    $filename= (strtolower(CHARSET) != 'utf-8') ? iconv('gbk', 'utf-8', $attachment->uploadedfiles[0]['filename']) : $attachment->uploadedfiles[0]['filename'];
                    if($attachment->uploadedfiles[0]['isimage']) {
                        echo $aids[0].','.$this->upload_url.$attachment->uploadedfiles[0]['filepath'].','.$attachment->uploadedfiles[0]['isimage'].','.$filename;
                    } else {
                        $fileext = $attachment->uploadedfiles[0]['fileext'];
                        if($fileext == 'zip' || $fileext == 'rar') $fileext = 'rar';
                        elseif($fileext == 'doc' || $fileext == 'docx') $fileext = 'doc';
                        elseif($fileext == 'xls' || $fileext == 'xlsx') $fileext = 'xls';
                        elseif($fileext == 'ppt' || $fileext == 'pptx') $fileext = 'ppt';
                        elseif ($fileext == 'flv' || $fileext == 'swf' || $fileext == 'rm' || $fileext == 'rmvb') $fileext = 'flv';
                        else $fileext = 'do';
                        echo $aids[0].','.$this->upload_url.$attachment->uploadedfiles[0]['filepath'].','.$fileext.','.$filename;
                    }
                    exit;
                } else {
                    echo '0,'.$attachment->error();
                    exit;

    这个里面有几行是比较重要的.

    首先它载入了系统的attachment类.并且用到了里面的方法.

    程序对上传成功做了echo操作.返回的东西是   返回了编号,上传后的地址,拓展名,文件名.

    这些东西是给谁用的啊   我们还得回去看配置文件.

    配置文件里面有一段是上传过程中各个事件将触发的方法.  有开始上传的.有上传成功的,有上传失败的.等等.

    我们可以看见有一个方法是file_dialog_complete_handler:fileDialogComplete,

    其实这些已经升级到swfupload的范畴了.有兴趣可以去研究研究

    然后我们在phpcms/static/swfupload/handler.js里面找到这个方法.

    看见上传成功后echo出来的数据被解析了.

    解析的方法如下

    复制代码 代码如下:

    function att_show(serverData,file)
    {
        var serverData = serverData.replace(//g,'');
        var data = serverData.split(',');
        var id = data[0];
        var src = data[1];
        var ext = data[2];
        var filename = data[3];
        if(id == 0) {
            alert(src)
            return false;
        }
        if(ext == 1) {
            var img = '
    ';
        } else {
            var img = '
    ';
        }
        $.get('index.php?m=attachment&c=attachments&a=swfupload_json&aid='+id+'&src='+src+'&filename='+filename);
        $('#fsUploadProgress').append('
  • ');
        $('#attachment_'+id).html(img);
        $('#att-status').append('|'+src);
        $('#att-name').append('|'+filename);
    }

    这个方法的目的是在id为fsuuploadprogress的元素里面添加我们上传成功的附件.但是我们还木有找到文件到底去哪里了

    关键的地方来了.我们在swfupload方法里面不是有个attachment的系统类的实例么

    真正上传附件是在这里实现的.我们调用了attachment里面的upload方法来实现了文件的上传.

    这个attachment文件里面的upload方法在系统类里面 也就是phpcms/libs/classes/attachment.class.php里面

    在这个类里面我们可以找到upload方法里面有这样一行

    复制代码 代码如下:

    $this->savepath = $this->upload_root.$this->upload_dir.date('Y/md/');

    这个自然就是指定了上传到的目录.文件名是通过getname方法来获取的.

    到这里我们就理清思路了.

    系统是这么运行的

    首先在模板里面引用swfupload(配置文件是用函数生成的)->上传文件->attachment模块里的swfupload方法处理(使用系统的attachment类里面的upload方法循环上传附件.并返回结果给swfupload方法)->处理结果通过swfupload的方法(fileDialogComplete)返回给页面.

    在上面我们已经实现了在模板里面引入swfupload.但是我们使用的配置文件和上传附件的方法等都是系统原来自带的.并不能实现我想要的目录结构和文件命名方法.怎么办..

    改.

    怎么改,首先们要把配置文件改掉. 在自己的模块里面的functions文件夹里面建立自己的函数.我们用自己的函数名称 文件命名为global.func.php这样系统会通过auto_load把我们的函数加载

    进去我们把系统中attachment模块functions文件夹下面的global.func.php里面的initupload函数全盘拷贝进来.只修改其中的一行

    复制代码 代码如下:

    upload_url:"'.APP_PATH.'index.php?m=你的模块名称&c=你的控制器名称&a=你的方法名称&dosubmit=1",

    这样文件就会提交到我们的控制器下面.并且调用我们自己写的方法

    然后我们去改系统的attachment类  我们在自己的模块下的classes文件夹下面建立一个myattachment.class.php

    写一个我们自己的类.去集成系统的attachment类.(记得吧里面的私有方法copy过来.)我们需要修改几行.首先一点是吧upload方法里面的上传目录改掉.然后是改掉文件名的命名方法.

    复制代码 代码如下:

    function upload($field, $alowexts = '', $maxsize = 0, $overwrite = 0,$thumb_setting = array(), $watermark_enable = 1) {
            if(!isset($_FILES[$field])) {
                $this->error = UPLOAD_ERR_OK;
                return false;
            }
            if(empty($alowexts) || $alowexts == '') {
                $site_setting = $this->_get_site_setting($this->siteid);
                $alowexts = $site_setting['upload_allowext'];
            }
            $fn = $_GET['CKEditorFuncNum'] ? $_GET['CKEditorFuncNum'] : '1';

            $this->field = $field;
            $this->savepath = $this->upload_root.$this->upload_dir.date('Ymd');//这里我们需要修改下.也可以不修改.在我们实例化这个类的时候再来指定目录.
            $this->alowexts = $alowexts;
            $this->maxsize = $maxsize;
            $this->overwrite = $overwrite;
            $uploadfiles = array();
            $description = isset($GLOBALS[$field.'_description']) ? $GLOBALS[$field.'_description'] : array();
            if(is_array($_FILES[$field]['error'])) {
                $this->uploads = count($_FILES[$field]['error']);
                foreach($_FILES[$field]['error'] as $key => $error) {
                    if($error === UPLOAD_ERR_NO_FILE) continue;
                    if($error !== UPLOAD_ERR_OK) {
                        $this->error = $error;
                        return false;
                    }
                    $uploadfiles[$key] = array('tmp_name' => $_FILES[$field]['tmp_name'][$key], 'name' => $_FILES[$field]['name'][$key], 'type' => $_FILES[$field]['type'][$key], 'size' => $_FILES[$field]['size'][$key], 'error' => $_FILES[$field]['error'][$key], 'description'=>$description[$key],'fn'=>$fn);
                }
            } else {
                $this->uploads = 1;
                if(!$description) $description = '';
                $uploadfiles[0] = array('tmp_name' => $_FILES[$field]['tmp_name'], 'name' => $_FILES[$field]['name'], 'type' => $_FILES[$field]['type'], 'size' => $_FILES[$field]['size'], 'error' => $_FILES[$field]['error'], 'description'=>$description,'fn'=>$fn);
            }

            if(!dir_create($this->savepath)) {
                $this->error = '8';
                return false;
            }
            if(!is_dir($this->savepath)) {
                $this->error = '8';
                return false;
            }
            @chmod($this->savepath, 0777);

            if(!is_writeable($this->savepath)) {
                $this->error = '9';
                return false;
            }
            if(!$this->is_allow_upload()) {
                $this->error = '13';
                return false;
            }
            $aids = array();
            foreach($uploadfiles as $k=>$file) {
                $fileext = fileext($file['name']);
                if($file['error'] != 0) {
                    $this->error = $file['error'];
                    return false;
                }
                if(!preg_match("/^(".$this->alowexts.")$/", $fileext)) {
                    $this->error = '10';
                    return false;
                }
                if($this->maxsize && $file['size'] > $this->maxsize) {
                    $this->error = '11';
                    return false;
                }
                if(!$this->isuploadedfile($file['tmp_name'])) {
                    $this->error = '12';
                    return false;
                }
                //$temp_filename = $this->getname($fileext);//名称在这里.我们需要修改下
           $temp_filename = $file['tmp_name'].$fileext; //修改成原来的系统文件名称.
           $savefile = $this->savepath.$temp_filename; $savefile = preg_replace("/(php|phtml|php3|php4|jsp|exe|dll|asp|cer|asa|shtml|shtm|aspx|asax|cgi|fcgi|pl)(.|$)/i", "_\1\2", $savefile); $filepath = preg_replace(new_addslashes("|^".$this->upload_root."|"), "", $savefile); if(!$this->overwrite && file_exists($savefile)) continue; $upload_func = $this->upload_func; if(@$upload_func($file['tmp_name'], $savefile)) { $this->uploadeds++; @chmod($savefile, 0644); @unlink($file['tmp_name']); $file['name'] = iconv("utf-8",CHARSET,$file['name']); $uploadedfile = array('filename'=>$file['name'], 'filepath'=>$filepath, 'filesize'=>$file['size'], 'fileext'=>$fileext, 'fn'=>$file['fn']); $thumb_enable = is_array($thumb_setting) && ($thumb_setting[0] > 0 || $thumb_setting[1] > 0 ) ? 1 : 0; $image = new image($thumb_enable,$this->siteid); if($thumb_enable) { $image->thumb($savefile,'',$thumb_setting[0],$thumb_setting[1]); } if($watermark_enable) { $image->watermark($savefile, $savefile); } $aids[] = $this->add($uploadedfile); } } return $aids; }


    注:这里我们可以再系统的attachment模块下建立MY_attachment.php  但是这样会影响系统的附件上传功能.

    在我们自己的控制器里面.我们这个时候就需要加载自己写的类了.

    复制代码 代码如下:

    pc_base::load_app_class('你的模块名','',0);

    The rest of the operations can be modified by referring to the swfupload method in the attachments controller under the attachment module of the system.

    At this point, I have accomplished my goal. I have completed the file upload function I want without changing the system file directory.

    www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326932.htmlTechArticleAfter formally contacting phpcms module development, I developed several functional modules. Among them, I encountered the problem of batch uploading of images. So I started to dig out the usage of swfupload in phpcms. In phpcms...
    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn