PHP简单实现切片上传

本篇仅作记录,不做教程,若需要详细讲解,请参考其它文章。

实现思路:

JS思路
1.监听上传按钮的onchange事件
2.获取文件的FILE对象
3.把文件的FILE对象进行切割,并且附加到FORMDATA对象中
4.把FORMDATA对象通过AJAX发送到服务器
5.重复3、4步骤,直到文件发送完。

PHP思路
1.建立上传文件夹
2.把文件从上传临时目录移动到上传文件夹
3.所有的文件块上传完成后,进行文件合成
4.删除文件夹
5.返回上传后的文件路径

前端代码:




    
    
    
    Document
    





 

PHP代码:

tmpPath =  $tmpPath;

        $this->blobNum =  $blobNum;

        $this->totalBlobNum =  $totalBlobNum;

        $this->fileName =  $fileName;

         

        $this->moveFile();

        $this->fileMerge();

    }

     

    //判断是否是最后一块,如果是则进行文件合成并且删除文件块

    private function fileMerge(){

        if($this->blobNum == $this->totalBlobNum){

            $blob = '';

            for($i=1; $i<= $this->totalBlobNum; $i++){

                $blob = file_get_contents($this->filepath.'/'. $this->fileName.'__'.$i);

                file_put_contents($this->filepath.'/'. $this->fileName,$blob,FILE_APPEND);

            }

             

           $this->deleteFileBlob();

        }

    }

     

   //删除文件块

    private function deleteFileBlob(){

        for($i=1; $i<= $this->totalBlobNum; $i++){

            @unlink($this->filepath.'/'. $this->fileName.'__'.$i);

        }

    }

     

    //移动文件

    private function moveFile(){

        $this->touchDir();

        $filename = $this->filepath.'/'. $this->fileName.'__'.$this->blobNum;

        move_uploaded_file($this->tmpPath,$filename);

    }

     

    //API返回数据

    public function apiReturn(){

        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'].dirname($_SERVER['SCRIPT_FILENAME']).str_replace('.','',$this->filepath).'/'. $this->fileName;

                    $data['blobNum'] = $this->blobNum;

                    $data['totalBlobNum'] = $this->totalBlobNum;


                }

        }else{

                if(file_exists($this->filepath.'/'. $this->fileName.'__'.$this->blobNum)){

                    $data['code'] = 1;

                    $data['msg'] = 'waiting for all';

                    $data['file_path'] = '';

                    $data['blobNum'] = $this->blobNum;

                    $data['totalBlobNum'] = $this->totalBlobNum;

                }

        }

        header('Content-type: application/json');

        echo json_encode($data);

    }

     

    //建立上传文件夹

    private function touchDir(){

        if(!file_exists($this->filepath)){

            return mkdir($this->filepath);

        }

    }

}

 
if (!isset($_POST['blob_num'])) {
    exit("error");
}
 

//实例化并获取系统变量传参
$upload = new Upload($_FILES['file']['tmp_name'],$_POST['blob_num'],$_POST['total_blob_num'],$_POST['file_name']);
//调用方法,返回结果
$upload->apiReturn();

以上代码均非原创,参考来源自哪个网站不记得了就不列出来了,仅作参考。

你可能感兴趣的:(前端,笔记,PHP)