From cc5b9d633b2091a1e63220b309aa463265c08aa2 Mon Sep 17 00:00:00 2001 From: fanguochao <544942125@qq.com> Date: Sat, 16 May 2020 18:12:47 +0800 Subject: [PATCH] =?UTF-8?q?'=E6=8F=90=E4=BA=A4=E4=B8=8A=E4=BC=A0=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E7=9A=84=E6=96=B9=E6=B3=95'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- demo.php | 18 +++- src/UploadLargeFiles/Upload.php | 147 ++++++++++++++++++++++++++++++++ 2 files changed, 163 insertions(+), 2 deletions(-) create mode 100644 src/UploadLargeFiles/Upload.php diff --git a/demo.php b/demo.php index 9a26c69..f8ebae6 100644 --- a/demo.php +++ b/demo.php @@ -1,5 +1,19 @@ $_FILES['file']['tmp_name'], // 文件内容 + 'now_package_num' => $_POST['blob_num'], // 当前文件包数量 + 'total_package_num' => $_POST['total_blob_num'], // 文件包总量 + 'file_name' => $_POST['file_name'], // 文件名称(唯一) + 'file_path' => './upload', // 文件存放路径 + 'clear_interval_time' => 60, // 清理临时文件间隔,默认五分钟 + 'is_continuingly' => true // 是否断点续传,默认为true +]; + +$upload->upload($config); \ No newline at end of file diff --git a/src/UploadLargeFiles/Upload.php b/src/UploadLargeFiles/Upload.php new file mode 100644 index 0000000..884e374 --- /dev/null +++ b/src/UploadLargeFiles/Upload.php @@ -0,0 +1,147 @@ +mkdir(); + } + + /** + * 主处理方法 + */ + public function upload(array $config=[]) { + // 初始化必要参数 + $this->init($config); + // 移动包 + $this->movePackage(); + // 合并包 + $this->mergePackage(); + // 检测并删除目录中是否存在过期临时文件 + $this->overdueFile(); + // 返回结果 + return $this->result(); + } + + /** + * 检测并删除目录中是否存在过期临时文件 + */ + private function overdueFile() { + $files = scandir(self::$filePath); + foreach ($files as $key => $val) { + if (strpos($val,self::FILE_SPLIT) !== false) { + $ctime = filectime(self::$filePath.'/'.$val); + $intervalTime = time()-$ctime+60*self::$clearIntervalTime; + if ($intervalTime<0) { + @unlink(self::$filePath.'/'.$val); + } + } + } + } + + /** + * 合并包 + */ + private function mergePackage(){ + + if(self::$nowPackageNum === self::$totalPackageNum){ + $blob = ''; + for($i=1; $i<= self::$totalPackageNum; $i++){ + $blob .= file_get_contents(self::$pathFileName.self::FILE_SPLIT.$i); + } + file_put_contents(self::$pathFileName, $blob); + $this->deletePackage(); + } + } + + /** + * 删除文件包 + */ + private function deletePackage(){ + for($i=1; $i<= self::$totalPackageNum; $i++){ + @unlink(self::$pathFileName.self::FILE_SPLIT.$i); + } + } + + /** + * 移动文件包 + */ + private function movePackage(){ + if (file_exists(self::$tmpPathFile) && self::$isContinuingly) { + return true; + } + move_uploaded_file(self::$tmpPath, self::$tmpPathFile); + } + + /** + * 上传结果 + */ + private function result(){ + if(self::$nowPackageNum === self::$totalPackageNum){ + return self::$pathFileName; + } + return 'ongoing'; + } + + /** + * 创建目录 + * @return bool + */ + private function mkdir(){ + if(!file_exists(self::$filePath)){ + return mkdir(self::$filePath); + } + } +} \ No newline at end of file