百度UEditor在線編輯器的配置和圖片上傳

前言

      最近在項目中使用了百度UEditor富文本編輯器,配置UEditor過程當中遇到了幾個問題,在此記錄一下解決方案和使用方法,避免之後使用UEditor出現相似的錯誤。css

基本配置

1、下載UEditor.NET版本開發包。html

UEditor能夠到 http://ueditor.baidu.com/website/download.html#ueditor 進行下載,咱們這裏選用1.4.3.3 .NET版本。jquery

QQ截圖20160815113251

2、把UEditor開發包放到項目裏面。web

一、新建一個ASP.NET MVC 4應用程序json

image

二、選擇基本項目模板。後端

image

三、把開發包的必要的文件放到項目裏面。服務器

首先咱們在項目Script目錄下新建一個ueditor文件夾用來保存圖1所示的JS文件,而後在項目根目錄建立一個Common文件夾用來保存圖2所示的後臺處理文件。mvc

圖1image 圖2image編輯器

四、在Views=>Shared=>_Layout.cshtml文件裏面引入UEditor必要的JS文件。測試

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    <script src="~/Scripts/ueditor/ueditor.config.js"></script>
    <script src="~/Scripts/ueditor/ueditor.all.js"></script>
    @RenderSection("scripts", required: false)
</body>
</html>

注意:ueditor.config.js和ueditor.all.js先後順序不能寫反了

五、建立UEditorController並添加視圖。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace UEditorDemo.Controllers
{
    public class UEditorController : Controller
    {
        [ValidateInput(false)]
        public ActionResult Index(FormCollection fc)
        {
            var content = fc["container"];
            return View();
        }
    }
}

注意:在Index Action上面要加上[ValidateInput(false)]特性

image

注意:在添加Index視圖的時候須要引入_Layout.cshtml母版頁。

在Index視圖裏面添加textarea標籤和相關JS代碼用來顯示編輯器,更多配置可參考ueditor.config.js裏面的配置說明。

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm("Index", "UEditor"))
{
    <textarea id="container" name="container"></textarea>
    <br />
    <input type="submit" value="提交" />
}

@section scripts{
    <script>
        $(function () {
            var editor = UE.getEditor('container', {
                minFrameHeight: 500,
                initialFrameHeight: 500,
                autoHeightEnabled: true,
            });
        });
    </script>
}

到目前爲止,正常狀況下,頁面上已經能顯示出來編輯器的樣子了。如今咱們輸入「測試」內容,點擊提交按鈕,後臺也能獲取到剛纔輸入的「測試」內容,如圖所示:

image

image

配置圖片上傳

在基本配置中,咱們能夠把文本內容上傳到服務器,這時候咱們想上傳一張圖片到服務器,發現上傳圖片的按鈕是禁用狀態,而且在打開多圖上傳對話框=>本地上傳選項卡顯示:後端配置項沒有正常加載。這是爲何呢?經過查找文檔發現是由於沒有配置ueditor.config.js文件的serverUrl屬性,如今讓咱們動手配置一下試試吧。

image

一、配置serverUrl屬性。

因爲咱們的controller.ashx放在Common文件夾下面,因此咱們打開ueditor.config.js文件把屬性serverUrl改成:

serverUrl: "/Common/controller.ashx"

二、配置圖片訪問路徑前綴和上傳保存路徑。

爲了可以讓圖片在編輯器裏面顯示,咱們還須要配置圖片訪問路徑前綴和上傳保存路徑。

1)打開Common文件夾下面的config.json文件,咱們把imageUrlPrefix屬性改成:

"imageUrlPrefix": "http://192.168.199.171/UploadFiles/", /* 圖片訪問路徑前綴 */

注意:須要在iis默認站點裏面添加一個別名爲「UploadFiles」的應用程序,並指定相應的物理路徑,上傳的圖片才能在編輯器裏面顯示。

2)把imagePathFormat屬性修改成:

"imagePathFormat": "/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,能夠自定義保存路徑和文件名格式 */

注意:在upload路徑前面加了一個「/」。

如今應該能夠上傳圖片並在編輯器裏面進行顯示了,以下圖所示:

image

image

圖片上傳進階

在實際的項目中,咱們上傳圖片可能保存在別的盤符下面以及訪問圖片的域名也須要改變,通常是後臺可配的,這時候咱們能夠經過修改後臺代碼實現這種需求。

一、修改UploadHandler.cs文件。

打開Common=>UploadHandler.cs文件找到下面的代碼,修改LocalPath和Result.Url變量便可獲得想要的效果。

var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat);  //修改地方1
var localPath = Server.MapPath(savePath);
try
{
    if (!Directory.Exists(Path.GetDirectoryName(localPath)))
    {
        Directory.CreateDirectory(Path.GetDirectoryName(localPath));
    }
    File.WriteAllBytes(localPath, uploadFileBytes);
    Result.Url = string.Format("http://192.168.199.171/sowerestres/Notice/{0}", savePath);  //修改地方2
    Result.State = UploadState.Success;
}
catch (Exception e)
{
    Result.State = UploadState.FileAccessError;
    Result.ErrorMessage = e.Message;
}
finally
{
    WriteResult();
}

二、修改ListFileHandler.cs文件。

打開Common=>ListFileHandler.cs文件找到下面的代碼,修改LocalPath和PathToList變量便可獲得想要的效果。

public ListFileManager(HttpContext context, string pathToList, string[] searchExtensions)
        : base(context)
    {
        this.SearchExtensions = searchExtensions.Select(x => x.ToLower()).ToArray();
        this.PathToList = "http://192.168.199.171/sowerestres/Notice/";  //修改地方1
    }
try
{
    var localPath = Server.MapPath(PathToList);  //修改地方2
    buildingList.AddRange(Directory.GetFiles(localPath, "*", SearchOption.AllDirectories)
        .Where(x => SearchExtensions.Contains(Path.GetExtension(x).ToLower()))
        .Select(x => PathToList + x.Substring(localPath.Length).Replace("\\", "/")));
    Total = buildingList.Count;
    FileList = buildingList.OrderBy(x => x).Skip(Start).Take(Size).ToArray();
}
catch (UnauthorizedAccessException)
{
    State = ResultState.AuthorizError;
}
catch (DirectoryNotFoundException)
{
    State = ResultState.PathNotFound;
}
catch (IOException)
{
    State = ResultState.IOError;
}
finally
{
    WriteResult();
}

 

以上是本人在.net mvc項目中使用ueditor編輯器的簡單配置,歡迎轉載和使用。

同時附上Demo下載地址:http://pan.baidu.com/s/1nvc0hAx (提取碼:61l0)

相關文章
相關標籤/搜索