PHP+JS实现文件分块上传的示例代码
发布时间:2023-02-16 12:51:55 所属栏目:PHP 来源:互联网
导读:我们在上传大文件时,可能会由于服务器的原因导致文件上传失败,文件过大时由于服务器的配置或响应事件过长导致上传文件失败,这时候我们可以将一个大的文件分为若干块,然后分批次上传到服务端,当所有文件块上传完成后再由服务器将各个文件块整合成我们上
/** * @var string 块文件临时存储的位置 */ private $tmpPath; /** * @var integer 第几个文件块 */ private $blobNum; /** * @var integer //文件块总数 */ private $totalBlobNum; /** * @var string 上传文件名 */ private $fileName; public function __construct($tmpPath, $blobNum,$totalBlobNum,$fileName, $filepath = ''){ if (!empty($filepath)) { $this->filepath = $filepath; } $this->tmpPath = $tmpPath; $this->blobNum = $blobNum; $this->totalBlobNum = $totalBlobNum; $this->fileName = $fileName; //保存文件块 $this->moveFile(); //保存文件 $this->fileMerge(); } private function fileMerge(){ //当文件块都上传后将文件块整合成文件 if($this->blobNum == $this->totalBlobNum){ for($i=1; $i<= $this->totalBlobNum; $i++){ $blob = ''; $blob = file_get_contents($this->filepath.'/'. $this->fileName.'__'.$i); file_put_contents($this->filepath.'/'. $this->fileName, $blob, FILE_APPEND ); unset($blob); } //删除文件块 $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); } //上传返回 public function uploadReturn(){ if($this->blobNum == $this->totalBlobNum){ if(file_exists($this->filepath.'/'. $this->fileName)){ return [ 'code' => 2, 'message' => 'success', 'file_path' => 'http://'.$_SERVER['HTTP_HOST'].str_replace('.','',$this->filepath).'/'. $this->fileName, 'local_path' => str_replace('.','',$this->filepath).'/'. $this->fileName ]; } } return [ 'code' => 1, 'message' => 'waiting', ]; } /** * 创建目录 */ private function touchDir(){ if(!file_exists($this->filepath)){ return mkdir($this->filepath); } } } 调用上传类 $tmpName = $_FILES['file']['tmp_name']; $blobNum = $_POST['blob_num']; $totalBlobNum = $_POST['total_blob_num']; $fileName = $_POST['file_name']; $upload = new Upload($tmpName, $blobNum, $totalBlobNum, $fileName); $data = $upload->uploadReturn(); header('Content-type: application/json'); return json_encode($data); (编辑:莱芜站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |