首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

ThinkPHP 3.2 圖片上傳與檔案管理控制器實作

     編輯:PHP 綜合知識

上傳端

public function file() {
    import('ORG.Net.UploadFile');
    import('ORG.Util.Services_JSON');

    $upload = new UploadFile();
    $upload->maxSize = 3145728; // 3MB
    $upload->allowExts = ['jpg', 'gif', 'png', 'jpeg'];
    $upload->savePath = './uploads/Images/';

    $info = $upload->uploadOne($_FILES['imgFile']);
    if ($info) {
        $url = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])) 
             . '/uploads/Images/' . $info[0]['savename'];
        echo (new Services_JSON())->encode(['error' => 0, 'url' => $url]);
    } else {
        $this->error($upload->getErrorMsg());
    }
}

檔案瀏覽端

public function file_manager() {
    import('ORG.Util.Services_JSON');
    $root = './uploads/Images/';
    $exts = ['gif', 'jpg', 'jpeg', 'png', 'bmp'];

    $dir = $_GET['dir'] ?? '';
    $path = $_GET['path'] ?? '';
    $order = $_GET['order'] ?? 'name';

    // 安全檢查
    if (!in_array($dir, ['', 'image', 'flash', 'media', 'file'])) exit('Invalid dir');
    if (strpos($path, '..') !== false) exit('Access denied');

    $current = realpath($root . $dir . $path) . '/';
    if (!is_dir($current)) exit('Directory not exist');

    $files = [];
    foreach (scandir($current) as $fn) {
        if ($fn[0] === '.') continue;
        $full = $current . $fn;
        $isDir = is_dir($full);
        $files[] = [
            'is_dir' => $isDir,
            'filename' => $fn,
            'filesize' => $isDir ? 0 : filesize($full),
            'is_photo' => !$isDir && in_array(strtolower(pathinfo($fn, PATHINFO_EXTENSION)), $exts),
            'datetime' => date('Y-m-d H:i:s', filemtime($full))
        ];
    }

    usort($files, function($a, $b) use ($order) {
        return strcmp($a[$order], $b[$order]);
    });

    echo (new Services_JSON())->encode([
        'moveup_dir_path' => dirname($path),
        'current_dir_path' => $path,
        'current_url' => '/uploads/Images/' . $dir . $path,
        'total_count' => count($files),
        'file_list' => $files
    ]);
}

前端整合建議

搭配 KindEditor / CKEditor 的 filebrowserBrowseUrl 指向 file_manager,即可實現圖片瀏覽、選取、上傳一站式體驗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved