濟南建站文匯軟件小編來帶大家了解下前端的切片斷點上傳
理清思路:
引入了兩個概念:塊(block)和片(chunk)。每個塊由一到多個片組成,而一個資源則由一到多個塊組成
塊是服務(wù)端的永久數(shù)據(jù)存儲單位,片則只在分片上傳過程中作為臨時存儲的單位。服務(wù)端會以約一個月為單位周期性的清除上傳后未被合并為塊的數(shù)據(jù)片。
實現(xiàn)過程:
將文件分割,分片上傳,然后合并。
前端代碼:
Document
后臺PHP代碼:
tmpPath = $tmpPath; $this->blobNum = $blobNum; $this->totalBlobNum = $totalBlobNum; // 文件名編碼 $this->fileName = iconv('utf-8','gbk', $fileName); $this->moveFile(); $this->fileMerge(); } //判斷是否是最后一塊,如果是則進(jìn)行文件合成并且刪除文件塊 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返回數(shù)據(jù) 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"); } //實例化并獲取系統(tǒng)變量傳參 $upload = new Upload($_FILES['file']['tmp_name'],$_POST['blob_num'],$_POST['total_blob_num'],$_POST['file_name']); //調(diào)用方法,返回結(jié)果 $upload->apiReturn(); ?>
親測有效,有興趣的同學(xué)可以自己動手實踐下。 希望這個小知識可以對你有所幫助,然后給濟南文匯軟件小編點個贊再走唄!
下一篇: css3的動畫屬性