PHP建站技术分享-从入门到精通PHP建站技术分享-从入门到精通PHP建站技术分享-从入门到精通

QQ:420220301 微信/手机:150-3210-7690
当前位置:首页 > CMS教程 > Fastadmin

fastadmin后台引入webupload做大文件上传

管理员 2024-12-14
Fastadmin
5
放入对应的js文件
在public/assets/js/目录里放入webuploader.js 和uploader.swf
在页面上创建对应的dom元素和样式处理 (本例子是在列表表格中使用) index.html
 <a href="javascript:;" class="btn btn-success {:$auth->check('xxxx')?'':'hide'}" title="文件上传" id="btn-origin-file"><i class="fa fa-upload"></i> <span class ='upload_text'>文件上传</span></a>  html页面底部增加个sytle<style type="text/css" media="all">    .webuploader-container {    position: relative;}.webuploader-element-invisible {    position: absolute !important;    clip: rect(1px 1px 1px 1px); /* IE6, IE7 */    clip: rect(1px,1px,1px,1px);}.webuploader-pick-disable {    opacity: 0.6;    pointer-events:none;}</style>
创建webuploader对象
找到你创建的对应页面的js文件@example : public/assets/js/backend/test.js头文件引入webuploaddefine(['jquery', 'bootstrap', 'backend', 'table', 'form','upload','webuploader'], function ($, undefined, Backend, Table, Form,Upload,WebUploader) {    // 初始化upload    var uploader = WebUploader.create({        // swf文件路径        swf:  'assets/js/Uploader.swf',            // 文件接收服务端。        server: 'dossier/upload',                chunked: true, //是否分片上传        chunkSize: 4 * 1024 * 1024, //10M        threads:5, //同时上传的线程数                pick: '#btn-origin-file',        // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!        resize: false    });        var Controller = {        index: function () {            // 初始化表格参数配置            Table.api.init({                extend: {                    index_url: 'dangan/dossier/index',                    add_url: 'dangan/dossier/add',                    edit_url: 'dangan/dossier/edit',                    del_url: 'dangan/dossier/del',                    import_url: 'dangan/dossier/import',                    multi_url: 'dangan/dossier/multi',                    origin_url: 'dangan/dossier/originfile',                    table: 'dossier',                }            });            var table = $("#table");            // 初始化表格            var data = [                //用你自己的            ]                                                // 为表格绑定事件            Table.api.bindevent(table);                                        uploader.on('uploadStart',function(){                        // 在这里设置一下上传的参数                uploader.options.formData = { "name": '12312', "id": 2};                            });            uploader.on( 'uploadProgress', function( file, percentage ) {                $(".upload_text").text( parseInt(percentage * 100) + '%');            });            uploader.on( 'uploadSuccess', function( file,response) {                $(".upload_text").text('上传电子文件');                 console.log("当前返回对象",response);                 Layer.alert("上传成功");                if(response.code && response.code == -1) {                     Layer.alert(response.msg);                }                      table.bootstrapTable('refresh', {});            });            uploader.on( 'uploadError', function( file ) {                $(".upload_text").text('上传电子文件');                 Layer.alert("上传失败")            });                                },        add: function () {            Controller.api.bindevent();        },        edit: function () {            Controller.api.bindevent();        },        api: {            bindevent: function () {                Form.api.bindevent($("form[role=form]"));            },        }    };    return Controller;});
php后台代码
文件: application/common/library/Upload.php<?php//Thanks https://github.com/linguochi/WebUploader_demonamespace appcommonlibrary;class Upload{    private $filepath = 'uploads/'; //上传目录    private $blobNum; //第几个文件块    private $totalBlobNum; //文件块总数    private $fileName; //文件名    #允许上传的文件    private $allowExtension = ['psd','jpg','jpeg'];    #文件后缀    private $fileExtension ='';    #当前块内容    private $nowFile = '';    #文件大小    private $totalSize = 0;    #文件总大小只允许2G    private $allowFileSize = 0;    #文件md5  前端传过来的   用于创建临时文件夹  上传完后删除    private $fileMd5 =  '';        public function __construct($savePath ='',$postData){              #测试断点上传             if($savePath){            $this->filepath = $this->filepath.$savePath."/";        }        #    #文件名称      #  var_dump($postData);        $postData['name'] =isset($postData['name']) ? $postData['name'] : '';        $this->fileName =$postData['name'];        if($this->isHaveFile()){            $this->ajaxReturn(['status'=>299,'msg'=>'文件已存在!']);        }        $pathinfo  = pathinfo($this->fileName);            $this->fileMd5 =md5($postData['name'].$postData['size'].$pathinfo['extension']);        // $this->fileMd5 =$postData['fileMd5'];        #允许文件的大小  2g        $this->allowFileSize =(2 * 1024 * 1024 * 1024);        if((int)$postData['size']>$this->allowFileSize){            $this->ajaxReturn(['status'=>204,'msg'=>"文件大小超2G限制!"]);        }        #文件大小        $this->totalSize=$postData['size'];        $postData['chunks']=isset($postData['chunks'])?(int)$postData['chunks']:1;        $postData['chunk']=isset($postData['chunk'])?(int)$postData['chunk']:0;        if(!(int)$postData['chunks']){            $this->ajaxReturn(['status'=>208,'msg'=>'chunks参数错误']);        }        #当前块        $this->blobNum = $postData['chunk']+1;        #总共块        $this->totalBlobNum = $postData['chunks'];        #获取后缀        $fileExtension =explode(".",basename( $this->fileName));        $this->fileExtension=array_pop($fileExtension);        #检测后缀是否在允许范围        $this->checkFileExtension();        $this->nowFile =  $_FILES['file'];        if( $this->nowFile['error'] > 0) {            $msg['status'] = 502;            $msg['msg'] = "文件错误!";            $this->ajaxReturn($msg);        }    }    function doUpload(){        #临时文件移动到指定目录下        $res = $this->moveFile();                $is_success = true;        $filePath = $this->filepath.$this->fileMd5."/";                for($i = 1; $i <= $this->totalBlobNum; $i++) {          if (!file_exists("{$filePath}{$i}.part")) {            $is_success = false;                                }        }          if( $is_success){                    // 再次尝试删除目录            return $this->fileMerge();                }else{            return $res;        }    }    #创建md5  文件名    function createFileName(){        return $this->filepath.$this->fileName;    }    #检测文件是否重复    function isHaveFile(){        if(file_exists($this->filepath.$this->fileName)){            return true;        }        return false;    }    #文件合并    function fileMerge(){            $fileName = $this->createFileName();        @unlink($fileName);        if(!$out = @fopen($fileName, "wb")){            return ['status' => '502','msg' => '文件权限有问题'];        }                for($i=1; $i<= $this->totalBlobNum; $i++) {                   $blockName = $this->filepath.$this->fileMd5."/".$i.'.part';            if (!$in = @fopen($blockName, "rb")) {                        break;            }            while ($buff = fread($in, 4096)) {                fwrite($out, $buff);            }            @fclose($in);            @unlink($blockName);        }       @fclose($out);        #删除临时目录        @rmdir($this->filepath.$this->fileMd5);        var_dump(filesize($fileName));        var_dump($this->totalSize);        if(filesize($fileName) == $this->totalSize){            $msg['status'] = 200;            $msg['msg'] = '上传成功!';            $msg['size'] = $this->totalSize;            $msg['filename'] = $this->createFileName();            $msg['name'] = $this->fileName;        }else{            $msg['status'] = 501;            $msg['msg'] = '上传文件大小和总大小有误!';            @unlink($this->createFileName());        }        return $msg;        # $this->ajaxReturn($msg);        }    #检测上传类型    function checkFileExtension(){        if(!in_array(strtolower($this->fileExtension),$this->allowExtension)){            $this->ajaxReturn(['status'=>203,'msg'=>"文件类型不允许"]);        }    }    #将临时文件移动到指定目录    function moveFile(){        try{            #每个块的文件名 以文件名的MD5作为命名            $filename=$this->createBlockFileName();            #分片文件写入            $handle=fopen($filename,"w+");            fwrite($handle,file_get_contents($this->nowFile ['tmp_name']));            fclose($handle);            #不是最后一块就返回当前信息   是最后一块往下执行合并操作            if($this->blobNum != $this->totalBlobNum) {                $msg['status'] = 201;                $msg['msg'] = "上传成功!";                $msg['blobNum'] = $this->blobNum;                return $msg;                #$this->ajaxReturn($msg);            }else{                $msg['status'] = 999;                $msg['msg'] = "上传成功!";                $msg['blobNum'] = $this->blobNum;                return $msg;            }        }catch (Exception $e){            $msg['status'] = 501;            $msg['error'] = $e->getMessage();            return $msg;            #$this->ajaxReturn($msg);        }    }    #创建分片文件名    function createBlockFileName(){        $dirName = $this->filepath.$this->fileMd5."/";        if (!is_dir($dirName) ) {            @mkdir($dirName, 0700);        };        return $dirName.$this->blobNum.".part";    }    #json格式放回处理    function ajaxReturn($msg){     return json_encode($msg);    }}
控制器调用
 public function upload(){        $model =new Upload(date("Ymd"),$this->request->post());        $res = $model->doUpload();        var_dump($res);}
总结
到这里 已经是上传文件和后台接收都完成..如需更多的配置请参考webuploader的官方配置文件

希望以上内容对你有所帮助!如果还有其他问题,请随时提问。 各类知识收集 拥有多年CMS企业建站经验,对 iCMS, Fastadmin, ClassCMS, LeCMS, PbootCMS, PHPCMS, 易优CMS, YzmCMS, 讯睿CMS, 极致CMS, Wordpress, HkCMS, YznCMS, WellCMS, ThinkCMF, 等各类cms的相互转化,程序开发,网站制作,bug修复,程序杀毒,插件定制都可以提供最佳解决方案。

相关推荐

扫码关注

qrcode

QQ交谈

回顶部