php 断点续传以及100% 后台zip解压

时间:2019-09-17
本文章向大家介绍php 断点续传以及100% 后台zip解压,主要包括php 断点续传以及100% 后台zip解压使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前台部分

 <div class="col-md-12">
                                
            <div class="form-group">
                <label class="control-label col-sm-2">申请人材料zip包</label>
                <div class="input-box col-sm-6">
                        <input class="btn btn-default" type="file" name="zipupload" id='zipupload' >
                        <input  type="hidden" id="file_zip_path" value=''/>
                       <span>
                         {foreach from=$upfiles[2] item=item}
                         <span>
                           <a href="{$item.dir}" target="_blank">{$item.file_name}</a>
                          <a href="javascript:void(0);" class="btn btn-default btn-sm" title="删除"<i class="glyphicon glyphicon-trash"></i></a>
                          </span>
                         {/foreach}

                        </span>
                        <span class="text-danger">上传的文件类型只支持zip格式</span>
                </div>
                <div class="zipparse" id="zipparse"></div>
              
                <div class="input-prompt col-sm-4 zipupload_error" for="research_field">
                    <div class="progress progress-striped">
                        <div id="filebar" class="progress-bar progress-bar-success" role="progressbar"
                             aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"
                             style="width: 0%;">
                            0%
                        </div>
                    </div>
                    zip格式
                </div>
            </div>                
       
                                          
        </div>
  <input type="hidden" name="url_class" id="url_class" value="ps/project">
    <input type="hidden" name="url_func" id="url_func" value="modify">
    <input type="hidden" name="proj_id" id="proj_id" value="{$proj_id}">
     <input type="hidden" name="ptype" id="ptype" value="{$ptype}">

js部分

<script type="text/javascript">
 var index=0;
        var uploadId="";
    $(function(){
        //onchange="getImg(this, '{$base_url}ps/project/projectAttachZip',4,{$proj_id},{$ptype})"
        var zipfiles=$("#zipupload");
       
        zipfiles.change(function(){
            var files = this.files; //获取上传文件的对象
            var file = files[0]; 
             sizes = file.size; //文件大小
              
            
             if (file.type!='application/zip') {
                 alert('您当前的上传类型不对,请上传zip格式');
                 return false;
             }
           
             blockSize = 1024 * 1024 * 2;//块大小
            var blockCount = Math.ceil(sizes / blockSize);//总块数
            //创建FormData对象
            var formData = new FormData();
            formData.append('fileName', file.name);//文件名
            formData.append('total', blockCount);//总块数
            formData.append('index', index);//当前上传的块下标
            formData.append('uploadId', uploadId);//块文件名
            formData.append('data', null);
            UploadFile(file, formData, sizes, blockCount, blockSize);
        });


    });

    function UploadFile(file, formData, sizes, blockCount, blockSize){
                
               
                var start=index*blockSize;
                var end = Math.min(sizes, start + blockSize);//获取结束块的大小
                 
              
                if (sizes<blockSize) {
                    var block = file.slice(0, sizes); //分割块
                } else {
                    var block = file.slice(start, end); //分割块
                }
                
                formData.set('proj_id', $('#proj_id').val()); //评审id
                 formData.set('ptype', $('#ptype').val());//评审类型
                 formData.set('data', block); //块
                 formData.set('index', index); //当前块
                 formData.set('uploadId', uploadId); //块id
                 $.ajax({
                     url: '/ps/project/ziptests',
                     type: 'post',
                     data: formData,
                     processData: false, //数据转换为对象
                     contentType: false,  //数据类型
                     dataType:'json',
                     success: function (res) {
                      
                         block = null;
                         if (res.Code === 1) {
                             if (index === 1)
                                 uploadId = res.UploadID;
 
                             $('#filebar').css('width',(index / blockCount * 100).toFixed(2) + '%');
                             $('#filebar').text((index / blockCount * 100).toFixed(2) + '%');
                             //上传完毕后开始解析文件内容
                             if ((index / blockCount * 100).toFixed(2)==100) {
                                 $("#file_zip_path").val(res.Path);
                                 
                                 $("#zipparse").wrap("<form id='ajaxupload' action='#' method='post' ></form>");
                              
                                
                                 {literal}
                                 $('#ajaxupload').ajaxSubmit({
                                     url: '#',
                                     dataType: "json",                                        //返回结果格式
                                     type: 'post',
                                     data: {file_path:$("#file_zip_path").val(),proj_id:$("#proj_id").val(),ptype:$("#ptype").val()},   //请求数据
                                     success: function (json) {

                                        $('.zipupload_error').html('<img src="/app/static/smartadmin/1.9.1/img/select2-spinner.gif" style="width: 50px"><span style="color: red">解析中......</span>');
                                        $.smallBox({
                                            title    : json.message,
                                            content  : "<i class='fa fa-clock-o'></i> 解析成功",
                                            color    : "#739e73",
                                            iconSmall: "fa fa-times fadeInRight",
                                            timeout  : 4000
                                        });

                                        $('.zipupload_error').html('<span>'+json.message+'</span>');

                                     },

                                 });
                               

                             }
                             if (index < blockCount) {
                                 index++;
                                 UploadFile(file, formData, sizes, blockCount, blockSize);
                             }
                         }
                     }
                 });
    }



    
</script>

后台部分

  //header('Content-type: application/json');
        $post=$this->input->post();
        $UploadID='';
        //首次上传
        if ($post['UploadID']=='') {
            $UploadID=$post['index'];
        }
        //文件名称
        $blockName = $UploadID.'.block';
        //文件上传路径
        $dir=APPPATH.'data/zip/'.intval($post['proj_id']).'/';
        $dir_path='/data/zip/'.intval($post['proj_id']).'/';
        mkDirs($dir);
        if (file_exists($dir.$post['fileName'])) {
                unlink($dir.$post['fileName']);
        }
        //块文件
        $blockpath=$dir.$blockName;
        if (file_exists($blockpath)) {
            echo json_encode(["Code"=>1, "Msg" => "文件已经存在~"]);
        }
        $data=file_get_contents($_FILES['data']['tmp_name']);
        
      
        //写块文件
        file_put_contents($blockpath,$data);
        //合并块文件
        if ($post['index']==$post['total']) {
            $bloacks='';
            $ext=pathinfo($post['fileName'],PATHINFO_EXTENSION);
            $filename=$dir.date('ymdhis',time()).'.'.$ext;
            $filename_path=$dir_path.date('ymdhis',time()).'.'.$ext;
            
            
             for($i=0;$i<=$post['total'];$i++) {
                 
                
                $bloacks.=file_get_contents($dir.$i.'.block');
                unlink($dir.$i.'.block');
                
                //echo $dir.md5($i).'_'.$i.'.block';
             }
             file_put_contents($filename,$bloacks);
            

            
        }
        
        echo json_encode(["Code"=>1, "Msg" => "上传成功~",'Path'=>$filename_path]);

zip解压部分

 /**
     * 文件编码
     *
     * @param [type] $fileName
     * @return void
     */
    function encodesutf8($name){
        $encoding = mb_detect_encoding($name,['UTF-8','GBK','BIG5','CP936']); //获取编码 然后转换
        if (DIRECTORY_SEPARATOR == '/'){    //linux widnwos下面是/
            $filename = iconv($encoding,'UTF-8',$fileName);
        }else{  //win
            $filename = iconv($encoding,'GBK',$fileName);
        }
        return $filename;
    }
 header('content-type:text/html;charset=utf-8');
       
        $proj_id=(int)$this->input->get('proj_id');
        $ptype=(int)$this->input->get('ptype');
        if($this->input->get('act') == 'do') {
           
        //     $config['upload_path'] = FCPATH.'data/upload/zip/';
        //  mkDirs($config['upload_path']);
        //  $config['allowed_types']= array('zip');
        //  $config['file_name'] = time().$_FILES['zipupload']['name'];
        //     $this->load->library('upload',$config);
            
            

        //  if(!$this->upload->do_upload('zipupload')){
        //      $this->smarty->error('评审意见表文件格式不符合规定');
        //  }
        
        //  $data=array(
        //      'filename'=>$_FILES['zipupload']['name'],
        //      'filepath'=>'/data/upload/zip/'.$this->upload->file_name,
        //    );

            $proj_id=(int)$this->input->post('proj_id');
            $ptype=(int)$this->input->post('ptype');
            $file_path=$this->input->post('file_path');

            
           
            
            $path=APPPATH.'data/upload/upfile/';
            
          
            $zip = new \ZipArchive;
            //$zipfile = APPPATH.'/data/upload/zip/'.$this->upload->file_name;
            $zipfile=APPPATH.$file_path;
           
            if (file_exists($zipfile)) {

            
            $zip->open($zipfile);
            $prefix_path="/data/upload/upfile/";
            if(!file_exists($path)) {
                mkDirs($path);
            }

            $docnum = $zip->numFiles;

            $annex=[
                'proj_id'=>$proj_id,
                'type'=>$ptype,
            ];

           
            $num_co=0;
            for($i = 0; $i < $docnum; $i++) {
                //获取所有的文件
                //$statInfo = $zip->getNameIndex($i);
                $statInfos = $zip->statIndex($i,\ZipArchive::FL_ENC_RAW);
                
               
                
                    $statInfo=$this->transcoding($statInfos['name']);
                    $exit=array_filter(explode('/',$statInfo));
                    
               

                //第一个是项目名称 第二个是申请名称 第三个是 附件材料
               
                
                
                 
                if (count($exit)>=3) {
                    $file_name=$exit[count($exit)-2]; //不用pathinfo是因为中文处理不好
                    $file_arr=explode('_',$file_name);
                    //获取是否出现以编号为结尾的文件夹名称
                   
                    if (empty($per_info)) {
                        continue;
                    }
                    
                
                        
                        
                       
                            copy('zip://'.$zipfile.'#'.$zip->getNameIndex($i), $path.$statInfo);
                        
                        
                } else {

                    continue;
                }
             
            }

            if (count($bool)==$num_co) {
                
                $this->smarty->success(basename($file_path),"#/ps/person/lists?proj_id=".$proj_id."&ptype=".$ptype);
            } else {
                $this->smarty->error($this->$oObject->data_error());
            }
         }
        }
      

$flag 上一页 下一页