asp.net core mvc 富文本编辑的实现

新闻消息等发布需要富文本编辑发布及修改。记录下:

1.采用kindeditor免费插件

2.kindeditor插件图片上传采用了iframe,默认违反了跨域访问的限制。需要将  [ValidateAntiForgeryToken]去掉。

3.具体配置.要求jquery在前面。

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="~/js/jquery.uniform.min.js"></script>
<link rel="stylesheet" href="~/lib/themes/default/default.css" />
<script src="~/lib/kindeditor-all-min.js"></script>
<script src="~/lib/lang/zh-CN.js"></script>

<script type="text/javascript">
    // 初始化 KindEditor
    KindEditor.ready(function (K) {
        window.editor = K.create('#editor', {
            width: '100%', // 编辑器宽度
            height: '500px', // 编辑器高度
            langType: 'zh-CN', // 设置为中文
            uploadJson: '/News/UploadImage', // 图片上传接口
            allowFileManager: false // 是否显示文件管理器
            
        });
         
    });
</script>

4.配合发布页面信息

    <form asp-action="Create">
   
    <div class="form-group">
        <label asp-for="Content" class="control-label"></label>
        <textarea id="editor"  asp-for="Content"></textarea>
        <span asp-validation-for="Content" class="text-danger"></span>
    </div>
   
    <div class="form-group">
        <input type="submit" value="Create" class="btn btn-primary" />
    </div>
</form>

5.create页面信息 正常写即可,kindeditor插件会将编辑内容以string类型放到textarea

  [HttpPost]
     
  public async Task<IActionResult> Create( News news)
  {
      if (ModelState.IsValid)
      {
          _context.Add(news);
          await _context.SaveChangesAsync();
          return RedirectToAction(nameof(Index));
      }
      return View(news);
  }

6.在controller里添加图片上传功能,图片上传到wwwroot下的文件夹。

  [HttpPost]
  public async Task<IActionResult> UploadImage(IFormFile imgFile)
  {
      if (imgFile == null || imgFile.Length == 0)
      {
          return Json(new { error = 1, message = "文件为空" });
      }

      // 检查文件类型
      var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif" };
      var fileExtension = Path.GetExtension(imgFile.FileName).ToLower();
      if (!allowedExtensions.Contains(fileExtension))
      {
          return Json(new { error = 1, message = "文件类型不支持" });
      }

      // 保存文件
      var uploadsFolder = Path.Combine(_env.WebRootPath, "uploads");
      if (!Directory.Exists(uploadsFolder))
      {
          Directory.CreateDirectory(uploadsFolder);
      }

      var fileName = Guid.NewGuid().ToString() + fileExtension;
      var filePath = Path.Combine(uploadsFolder, fileName);

      using (var stream = new FileStream(filePath, FileMode.Create))
      {
          await imgFile.CopyToAsync(stream);
      }

      // 返回 KindEditor 需要的 JSON 格式
      return Json(new
      {
          error = 0,
          url = $"/uploads/{fileName}"
      });
  }

7.修改同添加一样,但是delete要单独对图片进行删除,因为默认的只是删除了sqlserver里table的信息,文件夹下的图片需要格外处理。采用HtmlAgilityPack对table记录的string进行查找匹配处理。

   // POST: News/Delete/5
   [HttpPost, ActionName("Delete")]
   public async Task<IActionResult> DeleteConfirmed(int id)
   {
       var news = await _context.News.FindAsync(id);
      
       if (news != null)
       {
           _context.News.Remove(news);
           Removeimgs(news.Content);
       }

       await _context.SaveChangesAsync();
       return RedirectToAction(nameof(Index));
   }
   public void Removeimgs(string imgstrs)
   {
       var doc = new HtmlAgilityPack.HtmlDocument();
       doc.LoadHtml(imgstrs);
       var srcList = doc.DocumentNode.Descendants("img")
                       .Select(img => img.GetAttributeValue("src", ""))
                       .Where(s => !string.IsNullOrEmpty(s));
       foreach (var src in srcList) {
           if (!string.IsNullOrEmpty(src))
           {
               var oldFilePath =Path.Combine(_env.WebRootPath,src.TrimStart('/'));
               
               if (System.IO.File.Exists(oldFilePath))
               {
                   System.IO.File.Delete(oldFilePath);
               }
           }
       }
   }

8.在详细内容页面,需要将数据库中记录的string修改成html格式。

@Html.Raw(Model.Content)

​​​​​​

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值