<?php
namespace app\admin\controller\upload;
use app\common\controller\Backend;
use think\db;
use think\Request;
use ZipArchive;
/**
* 上傳功能
*
* @icon fa fa-user
*/
class Upload extends Backend{
protected $relationSearch = true;
public $file_path1 = "uploads/publishh.zip";
public $file_path2 = "E:\PHPTutorial\WWW\publishh";
public $file_path3 = "E:\PHPTutorial\WWW";
/**
* User模型對象
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = model('Player');
}
// 文件上傳表單
public function index(){
if(file_exists($this->file_path1)){
unlink($this->file_path1);
return $this->fetch();
}
else {
return $this->fetch();
}
}
//刪除文件夾以及文件夾里面所有的文件
public function deldir($dir) {
//先刪除目錄下的文件:
$dh=opendir($dir);
while ($file=readdir($dh)) {
if($file!="." && $file!="..") {
$fullpath=$dir."/".$file;
if(!is_dir($fullpath)) {
unlink($fullpath);
} else {
$this->deldir($fullpath);
}
}
}
closedir($dh);
//刪除當前文件夾:
if(@rmdir($dir)) {
return true;
} else {
return false;
}
}
//解壓一個壓縮包
/**
* 解壓zip文件到指定目錄
* $filepath: 文件路徑
* $extractTo: 解壓路徑
*/
public function dr_unZip($filepath,$extractTo) {
$zip = new ZipArchive;
$res = $zip->open($filepath);
if ($res === TRUE) {
//解壓縮到$extractTo指定的文件夾
$zip->extractTo($extractTo);
$zip->close();
echo "success改正";
} else {
echo 'failed, code:' . $res;
}
}
//判斷是否有子文件
public function hasFile($dirName) {
if(file_exists($dirName) && $handle = opendir($dirName)) {
while(false !== ($item = readdir($handle))) {
if($item!= "." && $item != ".."){
echo $item;
}
}
}
}
// 上傳文件方法
public function upload(){
if(file_exists($this->file_path1)){ //包含需要先刪除該wen
$unlink = unlink($this->file_path1);
if($unlink=true){
$file = request()->file('files');
if (empty($file)) {
$this->error('請選擇上傳文件');
}
// 移動到框架應用根目錄/public/uploads/ 目錄下
$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads','');
if ($info) {
$del = $this->deldir($this->file_path2);
if($del=true){
$row = $this->dr_unZip($this->file_path1,$this->file_path3);
if($row=true){
$this->success('文件上傳成功');
echo $info->getFilename();
}
}
else {
echo "刪除a目錄失敗";
}
}
else {
$this->error($file->getError());
}
}
else {
echo "刪除失敗";
}
}
else { //不包含就不用刪除了
$file = request()->file('files');
if (empty($file)) {
$this->error('請選擇上傳文件');
}
// 移動到框架應用根目錄/public/uploads/ 目錄下
$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads','');
if ($info) {
$del = $this->deldir($this->file_path2);
if($del=true){
$row = $this->dr_unZip($this->file_path1,$this->file_path3);
if($row=true){
$this->success('文件上傳成功');
echo $info->getFilename();
}
}
else {
echo "刪除a目錄失敗";
}
}
else {
$this->error($file->getError());
}
}
}
}