asp.net core集成CKEditor實現圖片上傳功能的示例代碼

背景

本文為大傢分享瞭asp.net core 如何集成CKEditor ,並實現圖片上傳功能的具體方法,供大傢參考,具體內容如下。

準備工作

1.visual studio 2019 開發環境

2.net core 2.0 及以上版本

實現方法

1、新建asp.net core web項目

2、下載CKEditor

這裡我們新建瞭一個系統自帶的樣本項目,去 CKEditor官網下載一個版本,解壓後拷貝大wwwroot中

3、增加圖片上傳控制器

@using CompanyName.ProjectName.Web.Host.Web.Model
@model demock
@{
  ViewData["title"] = "富文本框";
  Layout = "_SimpleTable";
}
@section headers{
  @*<style>
      .nav.nav-tabs.padding-18 {
        padding-left: 18px;
      }
      .nav-tabs {
        border-color: #c5d0dc;
        margin-bottom: 0 !important;
        margin-left: 0;
        position: relative;
        top: 1px;
      }
</style>*@
}

<section class="content">
  <div class="box box-primary">
    <div class="box-header with-border">
      <ul class="nav nav-tabs padding-18">
        <li>

          <a href="/demo/sendmail" rel="external nofollow" >
            <i class="orange ace-icon fa fa-cog bigger-120"></i>

            發郵件
          </a>
        </li>
        <li class="active">
          <a href="javascript:void(0);" rel="external nofollow" >

            <i class="green ace-icon fa fa-home bigger-120"></i>

            富文本編輯框
          </a>
        </li>
      </ul>
    </div>
    <!-- /.box-header -->
    <!-- form start -->
    <form role="form" id="form1">
      <div class="box-body">
        <div class="callout callout-success">
          <h4>富文本編輯器</h4>
          <p></p>
        </div>
        <table class="form">

          <tr>
            <th class="formTitle">內容</th>
            <td class="formValue">

              @Html.EditorFor(model => model.rules)

              @*<textarea class="form-control" name="Text" id="Text" style="height: 70px;" placeholder=""></textarea>*@
            </td>
          </tr>
        </table>
      </div>
      <!-- /.box-body -->
      <div class="box-footer">
        <button type="button" id="btnSave" class="btn btn-success">保存</button>
      </div>
    </form>
  </div>

  <!-- /.tab-content -->
</section>

@section scripts{

  <script src="~/ckeditor/ckeditor.js"></script>
  <script src="~/js/jquery.base64.js"></script>
  <script type="text/javascript">
  //editor.document.getBody().getText(); //取得純文本
  //editor.document.getBody().getHtml(); //取得html文本
  //var editor = CKEDITOR.replace('Text',
  //{
  //  toolbar: "Full",
  //  filebrowserUploadUrl: "/Image/ckupload?type=File", //開啟文件上傳(此項會同時開啟圖片和FLASH上傳)
  //  filebrowserImageUploadUrl: "/Image/ckupload?type=Images", // 開啟圖片上傳
  //  filebrowserFlashUploadUrl: "/Image/ckupload?type=Flash" //開啟FLASH上傳
  //});
    $.base64.utf8encode = true;
  var editor2 = CKEDITOR.replace('rules',
    {
      toolbar: "Full",
      filebrowserUploadUrl: "/Image/ckupload?type=File", //開啟文件上傳(此項會同時開啟圖片和FLASH上傳)
      filebrowserImageUploadUrl: "/Image/ckupload?type=Images", // 開啟圖片上傳
      filebrowserFlashUploadUrl: "/Image/ckupload?type=Flash" //開啟FLASH上傳
    });

  $(function () {
    editor2.setData("@(Html.Raw(Model.rules))");
  });
  $("#btnSave").click(function (ev) {

    var a = editor2.document.getBody().getHtml();

    $("#rules").val( $.base64.btoa(a) );
    var $form = $("#form1");
    editor2.setData(a);

    $.ajax({
      url: "/demo/ck/",
      data: $form.serialize(),
      type: "POST",
      cache: false,
      async: false,
      beforeSend: function () {
        $("#btnSave").attr("disabled", "disabled");
      },
      success: function (r) {

       // if (r.isSucceeded == true) {
          // location.href = r.goBackUrl;// "/Employee/index?ram=" + Math.random();// r.GoBackUrl;
        // }
       // else // 其他問題
       //  {
          alert( $.base64.atob(r.message, true));

      //  }
        $("#btnSave").removeAttr("disabled");
      },
      error: function () {

        alert("保存失敗");
        $("#btnSave").removeAttr("disabled");
      }
    });

   //  alert(editor2.document.getBody().getHtml());
    // return;
    //$.post("/demo/ck/",
    //  {

    //    Text: editor2.document.getBody().getHtml(),
    //  },
    //  function (data, status) {
    //     alert("Data: " + data + "\nStatus: " + status);

    //  });
  });
</script>

}
 /// <summary>
    /// 富文本框 上傳圖片
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [IgnoreAuthorize]
    public IActionResult Ckupload()
    {
      uploadfile user = new uploadfile();
      var files = Request.Form.Files;
      if (files == null || files.Count == 0)
        ViewBag.cc = "no file";
      user.ShareImg = files[0];
      var contentRoot = Directory.GetCurrentDirectory();
      var webRoot = Path.Combine(contentRoot, "wwwroot");
      var parsedContentDisposition = ContentDispositionHeaderValue.Parse(user.ShareImg.ContentDisposition);
      var originalName = parsedContentDisposition.FileName.ToString().Replace("\"", "");
      var ext = Path.GetExtension(Path.Combine(webRoot, originalName));
      //  if (ext != ".jpg")
      //  return Json(new { jsonrpc = "2.0", error = new { code = 101, message = "文件格式錯誤" }, id = "id" });
      string gid = Guid.NewGuid().ToString();
      var fileName = Path.Combine("upload", gid + ext);
      var fileName2 = "upload/" + gid + ext;
      using (var stream = new FileStream(Path.Combine(webRoot, fileName), FileMode.CreateNew))
      {
        user.ShareImg.CopyTo(stream);
      }
      string output = @"<script type=""text/javascript"">window.parent.CKEDITOR.tools.callFunction({0} ,'{1}');</script>";
      string url = "http://" + Request.Host.Value;
      output = string.Format(output, Request.Query["CKEditorFuncNum"], url + "/" + fileName2);
      ViewBag.cc = output;
      return View();
    }

4、增加圖片上傳控制器註意返回是一個json對象,因此建瞭一個

簡單的對象返回。

運行效果

源碼地址

https://gitee.com/conanOpenSource_admin/CompanyName.ProjectName

到此這篇關於asp.net core集成CKEditor實現圖片上傳功能的示例代碼的文章就介紹到這瞭,更多相關asp.net core CKEditor圖片上傳內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: