萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

UEditor 1.2.6 PHP 版安裝配置全流程指南(含圖片上傳修復)

百度 UEditor 是國內廣泛使用的富文本編輯器。本文以 PHP 版 1.2.6 為例,詳細記錄從下載、部署、前端整合、到解決「圖片上傳失效」的常見坑點全流程。

一、準備與部署

  1. 官網下載:https://ueditor.baidu.com/website/download.html(可按需精簡功能模組)
  2. 假設本地站點根目錄為 www/app/,將解壓後的 ueditor 資料夾放入:
    www/app/ueditor/
  3. 在 app/ 下建立 index.php 作為測試頁

二、前端整合代碼(index.php)

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>UEditor 完整版實例</title>
    <!-- 1. 載入配置 -->
    <script type="text/javascript" src="./ueditor/ueditor.config.js"></script>
    <!-- 2. 載入核心 JS -->
    <script type="text/javascript" src="./ueditor/ueditor.all.js"></script>
    <!-- 3. 載入主題樣式 -->
    <link rel="stylesheet" href="./ueditor/themes/default/css/ueditor.css" />
</head>
<body>
    <h2>UEditor 提交示例</h2>
    <form id="form" method="post" target="_blank">
        <!-- 編輯器容器:type="text/plain" 是關鍵 -->
        <script type="text/plain" id="myEditor" name="myEditor">
            <p>歡迎使用 UEditor!</p>
        </script>
        <input type="submit" value="通過 input submit 提交">
    </form>
    <p>
        1.2.6+ 版本自動同步數據,無需手動調用 sync()
        <button onclick="document.getElementById('form').submit()">JS 調用 submit 提交</button>
    </p>

    <script type="text/javascript">
        // 實例化編輯器,指定初始高度
        var editor = UE.getEditor('myEditor', { initialFrameHeight: 500 });

        // 動態設置表單提交地址(可根據後端路由調整)
        var form = document.getElementById('form');
        form.action = './getContent.php'; // 後端接收頁
    </script>
</body>
</html>

三、關鍵坑點:圖片上傳失效修復

刷新頁面後發現「插入圖片」無法上傳,控制台報錯路徑錯誤。原因是 ueditor.config.js 自動判斷路徑邏輯在某些目錄結構下失效。

修復步驟

  1. 打開 ueditor/ueditor.config.js
  2. 找到 var URL = window.UEDITOR_HOME_URL || (function(){ ... })();
  3. 在其上方插入一行,強制指定 UEditor 根路徑(以站點根目錄為基準):
window.UEDITOR_HOME_URL = "/app/ueditor/"; // 必須以 / 結尾

修改配置文件示意圖

  1. 保存並刷新頁面,圖片上傳功能恢復正常

四、後端接收範例

新建 getContent.php 接收提交內容:

<?php
header("Content-Type: text/html; charset=utf-8");
$content = isset($_POST['myEditor']) ? $_POST['myEditor'] : '';
echo '<h3>接收到的內容:</h3>';
echo $content; // 實際專案中進行過濾、存儲等邏輯
?>

五、常見配置調整(ueditor.config.js)

配置項說明建議值
imageUrl圖片上傳提交地址/app/ueditor/php/controller.php?action=uploadimage
imagePath圖片訪問路徑前綴/app/ueditor/php/
imageMaxSize圖片大小限制 (bytes)2048000 (2MB)
imageAllowFiles允許上傳副檔名[".png", ".jpg", ".jpeg", ".gif", ".bmp"]
catcherUrl遠程圖片抓取接口...?action=catchimage

注意: 官方文檔 https://ueditor.baidu.com/website/document.html 中部分文件名稱與實際版本不符,以解壓包內 php/controller.php 為準。

六、官方說明文檔補充

  • 後端控制器統一入口:php/controller.php,通過 action 參數分發(uploadimage, uploadfile, listimage 等)
  • 上傳目錄權限:確保 php/upload/ 目錄可寫(Linux 下 chmod 777)
  • 跨域上傳:若前後端分離,需在 controller.php 添加 header("Access-Control-Allow-Origin: *")

總結

UEditor 1.2.6 PHP 版部署核心三步:放文件、引資源、改路徑。重點記住 window.UEDITOR_HOME_URL 強制指定路徑,能省去 90% 的「圖片上傳不了」煩惱。後續可根據業務修改 controller.php 實現自定義存儲、水印、壓縮等高級功能。

copyright © 萬盛學電腦網 all rights reserved