在linux下使用百度ueditor編輯器上傳圖片

百度ueditor編輯器雖然強大,可是也有不足的地方。若是對ueditor流程不是很熟悉能夠說走的彎路比較多,費力不討好。下面呢,就是要解決ueditor遇到的問題。javascript

用ueditor上傳圖片遇到的問題是服務器錯誤php

雖然上傳成功可是服務器返回出錯,對於沒有經驗或者是初學者都回去百度搜,結果不是很理想。並且越走越偏。html

第一步:修改路徑文件config.jsonjava

/* 先後端通訊相關的配置,註釋只容許使用多行方式 */
{
    /* 上傳圖片配置項 */
    "imageActionName": "uploadimage", /* 執行上傳圖片的action名稱 */
    "imageFieldName": "upfile", /* 提交的圖片表單名稱 */
    "imageMaxSize": 4096000, /* 上傳大小限制,單位B */
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上傳圖片格式顯示 */
    "imageCompressEnable": true, /* 是否壓縮圖片,默認是true */
    "imageCompressBorder": 1600, /* 圖片壓縮最長邊限制 */
    "imageInsertAlign": "none", /* 插入的圖片浮動方式 */
    "imageUrlPrefix": "", /* 圖片訪問路徑前綴 */
    "imagePathFormat": "/public/ueditor/php/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,能夠自定義保存路徑和文件名格式 */
                                /* {filename} 會替換成原文件名,配置這項須要注意中文亂碼問題 */
                                /* {rand:6} 會替換成隨機數,後面的數字是隨機數的位數 */
                                /* {time} 會替換成時間戳 */
                                /* {yyyy} 會替換成四位年份 */
                                /* {yy} 會替換成兩位年份 */
                                /* {mm} 會替換成兩位月份 */
                                /* {dd} 會替換成兩位日期 */
                                /* {hh} 會替換成兩位小時 */
                                /* {ii} 會替換成兩位分鐘 */
                                /* {ss} 會替換成兩位秒 */
                                /* 非法字符 \ : * ? " < > | */
                                /* 具請體看線上文檔: fex.baidu.com/ueditor/#use-format_upload_filename */

    /* 塗鴉圖片上傳配置項 */
    "scrawlActionName": "uploadscrawl", /* 執行上傳塗鴉的action名稱 */
    "scrawlFieldName": "upfile", /* 提交的圖片表單名稱 */
    "scrawlPathFormat": "/ueditor/php/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,能夠自定義保存路徑和文件名格式 */
    "scrawlMaxSize": 2048000, /* 上傳大小限制,單位B */
    "scrawlUrlPrefix": "", /* 圖片訪問路徑前綴 */
    "scrawlInsertAlign": "none",

    /* 截圖工具上傳 */
    "snapscreenActionName": "uploadimage", /* 執行上傳截圖的action名稱 */
    "snapscreenPathFormat": "/ueditor/php/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,能夠自定義保存路徑和文件名格式 */
    "snapscreenUrlPrefix": "", /* 圖片訪問路徑前綴 */
    "snapscreenInsertAlign": "none", /* 插入的圖片浮動方式 */

    /* 抓取遠程圖片配置 */
    "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
    "catcherActionName": "catchimage", /* 執行抓取遠程圖片的action名稱 */
    "catcherFieldName": "source", /* 提交的圖片列表表單名稱 */
    "catcherPathFormat": "/ueditor/php/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,能夠自定義保存路徑和文件名格式 */
    "catcherUrlPrefix": "", /* 圖片訪問路徑前綴 */
    "catcherMaxSize": 2048000, /* 上傳大小限制,單位B */
    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取圖片格式顯示 */

    /* 上傳視頻配置 */
    "videoActionName": "uploadvideo", /* 執行上傳視頻的action名稱 */
    "videoFieldName": "upfile", /* 提交的視頻表單名稱 */
    "videoPathFormat": "/ueditor/php/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,能夠自定義保存路徑和文件名格式 */
    "videoUrlPrefix": "", /* 視頻訪問路徑前綴 */
    "videoMaxSize": 102400000, /* 上傳大小限制,單位B,默認100MB */
    "videoAllowFiles": [
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上傳視頻格式顯示 */

    /* 上傳文件配置 */
    "fileActionName": "uploadfile", /* controller裏,執行上傳視頻的action名稱 */
    "fileFieldName": "upfile", /* 提交的文件表單名稱 */
    "filePathFormat": "/ueditor/php/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,能夠自定義保存路徑和文件名格式 */
    "fileUrlPrefix": "", /* 文件訪問路徑前綴 */
    "fileMaxSize": 51200000, /* 上傳大小限制,單位B,默認50MB */
    "fileAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ], /* 上傳文件格式顯示 */

    /* 列出指定目錄下的圖片 */
    "imageManagerActionName": "listimage", /* 執行圖片管理的action名稱 */
    "imageManagerListPath": "/ueditor/php/upload/image/", /* 指定要列出圖片的目錄 */
    "imageManagerListSize": 20, /* 每次列出文件數量 */
    "imageManagerUrlPrefix": "", /* 圖片訪問路徑前綴 */
    "imageManagerInsertAlign": "none", /* 插入的圖片浮動方式 */
    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件類型 */

    /* 列出指定目錄下的文件 */
    "fileManagerActionName": "listfile", /* 執行文件管理的action名稱 */
    "fileManagerListPath": "/ueditor/php/upload/file/", /* 指定要列出文件的目錄 */
    "fileManagerUrlPrefix": "", /* 文件訪問路徑前綴 */
    "fileManagerListSize": 20, /* 每次列出文件數量 */
    "fileManagerAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ] /* 列出的文件類型 */

}

  咱們發現雖然改了隨意路徑(/public/ueditor/php/image/)上傳大小能夠根據本身的需求修改。可是還會服務器返回出錯,並且this request has no preview available(沒有任何請求)。linux

第二步:打開controller.php文件web

 1 <?php
 2 //header('Access-Control-Allow-Origin: http://www.baidu.com'); //設置http://www.baidu.com容許跨域訪問
 3 //header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); //設置容許的跨域header
 4 date_default_timezone_set("PRC"); 5 error_reporting(E_ERROR); 6 header("Content-Type: text/html; charset=utf-8"); 7 $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("config.json")), true); 8 $action = $_GET['action']; 9 switch ($action) { 10 case 'config': 11 $result = json_encode($CONFIG); 12 break; 13 14 /* 上傳圖片 */ 15 case 'uploadimage': 16 /* 上傳塗鴉 */ 17 case 'uploadscrawl': 18 /* 上傳視頻 */ 19 case 'uploadvideo': 20 /* 上傳文件 */ 21 case 'uploadfile': 22 $result = include("action_upload.php"); 23 break; 24 25 /* 列出圖片 */ 26 case 'listimage': 27 $result = include("action_list.php"); 28 break; 29 /* 列出文件 */ 30 case 'listfile': 31 $result = include("action_list.php"); 32 break; 33 34 /* 抓取遠程文件 */ 35 case 'catchimage': 36 $result = include("action_crawler.php"); 37 break; 38 39 default: 40 $result = json_encode(array( 41 'state'=> '請求地址出錯' 42  )); 43 break; 44 } 45 46 /* 輸出結果 */ 47 if (isset($_GET["callback"])) { 48 if (preg_match("/^[\w_]+$/", $_GET["callback"])) { 49 echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')'; 50 } else { 51 echo json_encode(array( 52 'state'=> 'callback參數不合法' 53  )); 54  } 55 } else { 56 echo $result; 57 }菜鳥在調試controller.php常常忽略date_default_timezone_set("PRC");禁止顯示錯誤。
咱們發現error_reporting(E_ERROR);關於ueditor資料遇到上傳不成功都會說路徑,而不會說controller.php文件下:error_reporting(E_ERROR)。能夠修改爲error_reporting(E_ALL)能夠看到

報錯位置是Uploader.class.php on line 248。
第三步:打開Uploader.class.php  
<?php

/**
 * Created by JetBrains PhpStorm.
 * User: taoqili
 * Date: 12-7-18
 * Time: 上午11: 32
 * UEditor編輯器通用上傳類
 */
class Uploader
{
    private $fileField; //文件域名
    private $file; //文件上傳對象
    private $base64; //文件上傳對象
    private $config; //配置信息
    private $oriName; //原始文件名
    private $fileName; //新文件名
    private $fullName; //完整文件名,即從當前配置目錄開始的URL
    private $filePath; //完整文件名,即從當前配置目錄開始的URL
    private $fileSize; //文件大小
    private $fileType; //文件類型
    private $stateInfo; //上傳狀態信息,
    private $stateMap = array( //上傳狀態映射表,國際化用戶需考慮此處數據的國際化
        "SUCCESS", //上傳成功標記,在UEditor中內不可改變,不然flash判斷會出錯
        "文件大小超出 upload_max_filesize 限制",
        "文件大小超出 MAX_FILE_SIZE 限制",
        "文件未被完整上傳",
        "沒有文件被上傳",
        "上傳文件爲空",
        "ERROR_TMP_FILE" => "臨時文件錯誤",
        "ERROR_TMP_FILE_NOT_FOUND" => "找不到臨時文件",
        "ERROR_SIZE_EXCEED" => "文件大小超出網站限制",
        "ERROR_TYPE_NOT_ALLOWED" => "文件類型不容許",
        "ERROR_CREATE_DIR" => "目錄建立失敗",
        "ERROR_DIR_NOT_WRITEABLE" => "目錄沒有寫權限",
        "ERROR_FILE_MOVE" => "文件保存時出錯",
        "ERROR_FILE_NOT_FOUND" => "找不到上傳文件",
        "ERROR_WRITE_CONTENT" => "寫入文件內容錯誤",
        "ERROR_UNKNOWN" => "未知錯誤",
        "ERROR_DEAD_LINK" => "連接不可用",
        "ERROR_HTTP_LINK" => "連接不是http連接",
        "ERROR_HTTP_CONTENTTYPE" => "連接contentType不正確",
        "INVALID_URL" => "非法 URL",
        "INVALID_IP" => "非法 IP"
    );

    /**
     * 構造函數
     * @param string $fileField 表單名稱
     * @param array $config 配置項
     * @param bool $base64 是否解析base64編碼,可省略。若開啓,則$fileField表明的是base64編碼的字符串表單名
     */
    public function __construct($fileField, $config, $type = "upload")
    {
        $this->fileField = $fileField;
        $this->config = $config;
        $this->type = $type;
        if ($type == "remote") {
            $this->saveRemote();
        } else if($type == "base64") {
            $this->upBase64();
        } else {
            $this->upFile();
        }

        $this->stateMap['ERROR_TYPE_NOT_ALLOWED'] = iconv('unicode', 'utf-8', $this->stateMap['ERROR_TYPE_NOT_ALLOWED']);
    }

    /**
     * 上傳文件的主處理方法
     * @return mixed
     */
    private function upFile()
    {
        $file = $this->file = $_FILES[$this->fileField];
        if (!$file) {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            return;
        }
        if ($this->file['error']) {
            $this->stateInfo = $this->getStateInfo($file['error']);
            return;
        } else if (!file_exists($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
            return;
        } else if (!is_uploaded_file($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
            return;
        }

        $this->oriName = $file['name'];
        $this->fileSize = $file['size'];
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //檢查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //檢查是否不容許的文件格式
        if (!$this->checkType()) {
            $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
            return;
        }

        //建立目錄失敗
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            //$this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            $this->stateInfo = $dirname;
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        //移動文件
        if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移動失敗
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
        } else { //移動成功
            $this->stateInfo = $this->stateMap[0];
        }
    }

    /**
     * 處理base64編碼的圖片上傳
     * @return mixed
     */
    private function upBase64()
    {
        $base64Data = $_POST[$this->fileField];
        $img = base64_decode($base64Data);

        $this->oriName = $this->config['oriName'];
        $this->fileSize = strlen($img);
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //檢查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //建立目錄失敗
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            //$this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            $this->stateInfo = $dirname;
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        //移動文件
        if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移動失敗
            $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
        } else { //移動成功
            $this->stateInfo = $this->stateMap[0];
        }

    }

    /**
     * 拉取遠程圖片
     * @return mixed
     */
    private function saveRemote()
    {
        $imgUrl = htmlspecialchars($this->fileField);
        $imgUrl = str_replace("&amp;", "&", $imgUrl);

        //http開頭驗證
        if (strpos($imgUrl, "http") !== 0) {
            $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
            return;
        }

        preg_match('/(^https*:\/\/[^:\/]+)/', $imgUrl, $matches);
        $host_with_protocol = count($matches) > 1 ? $matches[1] : '';

        // 判斷是不是合法 url
        if (!filter_var($host_with_protocol, FILTER_VALIDATE_URL)) {
            $this->stateInfo = $this->getStateInfo("INVALID_URL");
            return;
        }

        preg_match('/^https*:\/\/(.+)/', $host_with_protocol, $matches);
        $host_without_protocol = count($matches) > 1 ? $matches[1] : '';

        // 此時提取出來的多是 ip 也有多是域名,先獲取 ip
        $ip = gethostbyname($host_without_protocol);
        // 判斷是不是私有 ip
        if(!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
            $this->stateInfo = $this->getStateInfo("INVALID_IP");
            return;
        }

        //獲取請求頭並檢測死鏈
        $heads = get_headers($imgUrl, 1);
        if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
            $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
            return;
        }
        //格式驗證(擴展名驗證和Content-Type驗證)
        $fileType = strtolower(strrchr($imgUrl, '.'));
        if (!in_array($fileType, $this->config['allowFiles']) || !isset($heads['Content-Type']) || !stristr($heads['Content-Type'], "image")) {
            $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
            return;
        }

        //打開輸出緩衝區並獲取遠程圖片
        ob_start();
        $context = stream_context_create(
            array('http' => array(
                'follow_location' => false // don't follow redirects
            ))
        );
        readfile($imgUrl, false, $context);
        $img = ob_get_contents();
        ob_end_clean();
        preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);

        $this->oriName = $m ? $m[1]:"";
        $this->fileSize = strlen($img);
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //檢查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //建立目錄失敗
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            //$this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
        this->stateInfo = $dirname;
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        //移動文件
        if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移動失敗
            $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
        } else { //移動成功
            $this->stateInfo = $this->stateMap[0];
        }

    }

    /**
     * 上傳錯誤檢查
     * @param $errCode
     * @return string
     */
    private function getStateInfo($errCode)
    {
        return !$this->stateMap[$errCode] ? $this->stateMap["ERROR_UNKNOWN"] : $this->stateMap[$errCode];
    }

    /**
     * 獲取文件擴展名
     * @return string
     */
    private function getFileExt()
    {
        return strtolower(strrchr($this->oriName, '.'));
    }

    /**
     * 重命名文件
     * @return string
     */
    private function getFullName()
    {
        //替換日期事件
        $t = time();
        $d = explode('-', date("Y-y-m-d-H-i-s"));
        $format = $this->config["pathFormat"];
        $format = str_replace("{yyyy}", $d[0], $format);
        $format = str_replace("{yy}", $d[1], $format);
        $format = str_replace("{mm}", $d[2], $format);
        $format = str_replace("{dd}", $d[3], $format);
        $format = str_replace("{hh}", $d[4], $format);
        $format = str_replace("{ii}", $d[5], $format);
        $format = str_replace("{ss}", $d[6], $format);
        $format = str_replace("{time}", $t, $format);

        //過濾文件名的非法自負,並替換文件名
        $oriName = substr($this->oriName, 0, strrpos($this->oriName, '.'));
        $oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $oriName);
        $format = str_replace("{filename}", $oriName, $format);

        //替換隨機字符串
        $randNum = rand(1, 10000000000) . rand(1, 10000000000);
        if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
            $format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
        }

        $ext = $this->getFileExt();
        return $format . $ext;
    }

    /**
     * 獲取文件名
     * @return string
     */
    private function getFileName () {
        return substr($this->filePath, strrpos($this->filePath, '/') + 1);
    }

    /**
     * 獲取文件完整路徑
     * @return string
     */
    private function getFilePath()
    {
        $fullname = $this->fullName;
        $rootPath = $_SERVER['DOCUMENT_ROOT'];

        if (substr($fullname, 0, 1) != '/') {
            $fullname = '/' . $fullname;
        }

        return $rootPath . $fullname;
    }

    /**
     * 文件類型檢測
     * @return bool
     */
    private function checkType()
    {
        return in_array($this->getFileExt(), $this->config["allowFiles"]);
    }

    /**
     * 文件大小檢測
     * @return bool
     */
    private function  checkSize()
    {
        return $this->fileSize <= ($this->config["maxSize"]);
    }

    /**
     * 獲取當前上傳成功文件的各項信息
     * @return array
     */
    public function getFileInfo()
    {
        return array(
            "state" => $this->stateInfo,
            "url" => $this->fullName,
            "title" => $this->fileName,
            "original" => $this->oriName,
            "type" => $this->fileType,
            "size" => $this->fileSize
        );
    }

}

發現248行因爲誤刪,致使報錯。那咱們就修改248行代碼。修改完成後再次刷新/ueditor/php/controller.php?action=uploadimage&encode=utf-8頁面。json

刷新頁面完成又報/ueditor/php/Uploader.class.php on line 66 無論它。咱們再次開啓error_reporting(E_ERROR);後端

咱們試一次看看是否成功跨域

成功了(備註:在linux系統下修改路徑要注意權限)。服務器

相關文章
相關標籤/搜索