美文网首页
分片上传文件处理

分片上传文件处理

作者: blank喵 | 来源:发表于2021-02-25 11:53 被阅读0次
    此需要基于webuploader.js插件
    1. 前端代码
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>webuploader</title>
    </head>
    <!--引入CSS-->
    <link rel="stylesheet" type="text/css" href="/static/plugin/webuploader-0.1.5/webuploader.css">
    <style>
        #upload-container, #upload-list{width: 500px; margin: 0 auto; }
        #upload-container{cursor: pointer; border-radius: 15px; background: #EEEFFF; height: 200px;}
        #upload-list{height: 800px; border: 1px solid #EEE; border-radius: 5px; margin-top: 10px; padding: 10px 20px;}
        #upload-container>span{widows: 100%; text-align: center; color: gray; display: block; padding-top: 15%;}
        .upload-item{margin-top: 5px; padding-bottom: 5px; border-bottom: 1px dashed gray;}
        .percentage{height: 5px; background: green;}
        .btn-delete, .btn-retry{cursor: pointer; color: gray;}
        .btn-delete:hover{color: orange;}
        .btn-retry:hover{color: green;}
    </style>
    <!--引入JS-->
    <body>
    <div id="upload-container">
        <span>点击或将文件拖拽至此上传</span>
    </div>
    <div id="upload-list">
        <!-- <div class="upload-item">
            <span>文件名:123</span>
            <span data-file_id="" class="btn-delete">删除</span>
            <span data-file_id="" class="btn-retry">重试</span>
            <div class="percentage"></div>
        </div> -->
    </div>
    <button id="picker" style="display: none;">点击上传文件</button>
    </body>
    <script type="text/javascript" src="https://jq.woshitime.top/jquery-3.5.1.min.js"></script>
    <script type="text/javascript" src="/static/plugin/webuploader-0.1.5/webuploader.js"></script>
    <script>
        $('#upload-container').click(function(event) {
            $("#picker").find('input').click();
        });
        var uploader = WebUploader.create({
            auto: true,// 选完文件后,是否自动上传。
            swf: '/static/plugin/webuploader-0.1.5/Uploader.swf',
            // 文件接收服务端。
            server: '{:Url("Index/fileupload")}',
            dnd: '#upload-container',
            pick: '#picker',// 内部根据当前运行是创建,可能是input元素,也可能是flash. 这里是div的id
            // multiple: true, // 选择多个
            chunked: true,// 开起分片上传。
            threads: 1, // 上传并发数。允许同时最大上传进程数。
            // method: 'POST', // 文件上传方式,POST或者GET。
            chunkSize:10*1024, //*1024*1024分片上传,每片2M,默认是5M
            fileVal:'upload', // [默认值:'file'] 设置文件上传域的name。
        });
    
        uploader.on('fileQueued', function(file) {
            // 选中文件时要做的事情,比如在页面中显示选中的文件并添加到文件列表,获取文件的大小,文件类型等
            // console.log(file.ext) // 获取文件的后缀
            // console.log(file.size) // 获取文件的大小
            // console.log(file.name);
            var html = '<div class="upload-item"><span>文件名:'+file.name+'</span><span data-file_id="'+file.id+'" class="btn-delete">删除</span><span data-file_id="'+file.id+'" class="btn-retry">重试</span><div class="percentage '+file.id+'" style="width: 0%;"></div></div>';
            $('#upload-list').append(html);
        });
    
        uploader.on('uploadProgress', function(file, percentage) {
            console.log(percentage * 100 + '%');
            var width = $('.upload-item').width();
            $('.'+file.id).width(width*percentage);
        });
    
        uploader.on('uploadSuccess', function(file, response) {
            console.log(file.id+"传输成功");
        });
    
        uploader.on('uploadError', function(file) {
            console.log(file);
            console.log(file.id+'上传出错')
        });
    
        $('#upload-list').on('click', '.upload-item .btn-delete', function() {
            // 从文件队列中删除某个文件id
            var file_id = $(this).data('file_id');
            // uploader.removeFile(file_id); // 标记文件状态为已取消
            uploader.removeFile(file_id, true); // 从queue中删除
            console.log(uploader.getFiles());
        });
    
        $('#upload-list').on('click', '.btn-retry', function() {
            uploader.retry($(this).data('file_id'));
        });
    
        uploader.on('uploadComplete', function(file) {
            console.log(uploader.getFiles());
        });
    </script>
    </html>
    
    2. 后端代码
    
    class upload
    {
        private $filepath = './webuploader'.DIRECTORY_SEPARATOR.'file_material'; //上传目录
        private $fileTmpPath = './webuploader'.DIRECTORY_SEPARATOR.'file_material_tmp'; //上传目录
        private $tmpPath; //PHP文件临时目录
        private $blobNum; //第几个文件块
        private $totalBlobNum; //文件块总数
        private $fileName; //文件名
    
        public function __construct($tmpPath,$blobNum,$totalBlobNum,$fileName){
            $this->tmpPath = $tmpPath;
            $this->blobNum = $blobNum;
            $this->totalBlobNum = $totalBlobNum-1;
            $this->fileName = $fileName;
    
            $this->moveFile();
            $this->fileMerge();
        }
    
        //判断是否是最后一块,如果是则进行文件合成并且删除文件块
        private function fileMerge(){
            if($this->blobNum == $this->totalBlobNum){
                $blob = '';
                for($i=0; $i<= $this->totalBlobNum; $i++){
                    $blob .= file_get_contents($this->fileTmpPath.'/'. $this->fileName.'__'.$i);
                }
                file_put_contents($this->filepath.'/'. $this->fileName,$blob);
                $this->deleteFileBlob();
            }
        }
    
        //删除文件块
        private function deleteFileBlob(){
            for($i=0; $i<= $this->totalBlobNum; $i++){
                @unlink($this->fileTmpPath.'/'. $this->fileName.'__'.$i);
            }
        }
    
        //移动文件
        private function moveFile(){
            $this->touchDir();
            $filename = $this->fileTmpPath.'/'. $this->fileName.'__'.$this->blobNum;
            move_uploaded_file($this->tmpPath,$filename);
        }
    
        //API返回数据
        public function apiReturn(){
            $data = [];
            if($this->blobNum == $this->totalBlobNum){
                if(file_exists($this->filepath.'/'. $this->fileName)){
                    $data['code'] = 2;
                    $data['msg'] = 'success';
                    $data['file_path'] = 'http://'.$_SERVER['HTTP_HOST'].str_replace('.','',$this->filepath).'/'. $this->fileName;
                }
            }else{
                if(file_exists($this->fileTmpPath.'/'. $this->fileName.'__'.$this->blobNum)){
                    $data['code'] = 1;
                    $data['msg'] = 'waiting for all';
                    $data['file_path'] = '';
                }
            }
            return json_encode($data);
        }
    
        //建立上传文件夹
        private function touchDir(){
            if(!file_exists($this->filepath)){
                if (!mkdir($concurrentDirectory = $this->filepath) && !is_dir($concurrentDirectory)) {
                    throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
                }
            }
            if(!file_exists($this->fileTmpPath)){
                if (!mkdir($concurrentDirectory = $this->fileTmpPath) && !is_dir($concurrentDirectory)) {
                    throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
                }
            }
        }
    }
    
    3. 控制器代码
    public function fileupload()
    {
        $file = $_FILES['upload'];
    
        $id = input("id");
        $fileName = cache($id);
        if (!$fileName){
            $fileName = md5(time().uniqid(random_int(0,99999),true)).'.'.pathinfo($file['name'])['extension'];
        }
        cache($id,$fileName,10);
        $chunk = input("chunk",0);
        $chunks = input("chunks",1);
    
        $upload = new upload($file['tmp_name'],$chunk,$chunks,$fileName);
        echo $upload->apiReturn();
    }
    

    相关文章

      网友评论

          本文标题:分片上传文件处理

          本文链接:https://www.haomeiwen.com/subject/pqgyfltx.html