本項目是一個.net core的mvc項目
1.下載kindeditor 4.1.11 解壓後將文件夾置於 wwwroot目錄下,如圖:
2.在HomeController的Index控制器對應的index視圖輸入一下代碼:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>我是管理員首頁</title>
@*首先要引入關鍵的兩個js*@
<script charset="utf-8" src="/kindeditor/kindeditor-all-min.js"></script>
<script charset="utf-8" src="/kindeditor/lang/zh-CN.js"></script>
@*創建KindEditor對象*@
<script>
KindEditor.ready(function (K) {
K.create('#editor_id', {
//注意kindeditor包裏面自帶的是一個ashx的一班處理程序 此處改爲mvc的控制器方法
uploadJson: '@Url.Action("KindeditorPicUpload", "KEUpload")',
//fileManagerJson: '/kindeditor/asp.net/file_manager_json.ashx',
allowFileManager: true
});
});
</script>
</head>
<body>
<div>管理從此開始</div>
<form action="/home/index" method="post">
<div>
<textarea id="editor_id" name="content" style="width:700px;height:300px;">
<strong>HTML內容</strong>
</textarea>
</div>
<div><input type="submit" value="提交" /></div>
</form>
</body>
</html>
3.在以上代碼中 使用到了KindeditorPicUpload控制的KEUpload用於處理文本編輯器裏面的圖片上傳
下面是這個控制器代碼:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;
using System.Net.Http.Headers;
namespace Kdeditor.Start.Controllers
{
public class KEUploadController : Controller
{
private IHostingEnvironment hostingEnv;
public IActionResult Index()
{
return View();
}
public KEUploadController(IHostingEnvironment env)
{
this.hostingEnv = env;
}
/// <summary>
/// Kindeditor圖片上傳
/// </summary>
/// <param name="imgFile">Kindeditor圖片上傳自帶的命名,不可更改名稱</param>
/// <param name="dir">不可更改名稱 這裏沒有用到dir</param>
/// <returns></returns>
public IActionResult KindeditorPicUpload(IList<IFormFile> imgFile, string dir)
{
//http://www.cnblogs.com/fireicesion/p/9490901.html
//https://www.cnblogs.com/fishpro/p/how_upload_pic_with_kindeditor_for_asp_net_core.html
//注意 如果是上傳到本地這個文件夾子 那麼事先必須創建這個文件夾
PicUploadResponse rspJson = new PicUploadResponse() { error = 0, url = "/upload/" };
long size = 0;
string tempname = "";
foreach (var file in imgFile)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
//獲取每個圖片的擴展名
var extname = filename.Substring(filename.LastIndexOf("."), filename.Length - filename.LastIndexOf("."));
//創建新的文件名 guid+擴展名
var filename1 = System.Guid.NewGuid().ToString() + extname;
tempname = filename1;
var path = hostingEnv.WebRootPath;
filename = hostingEnv.WebRootPath + $@"\upload\{filename1}";
size += file.Length;
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
//這裏是業務邏輯
}
}
rspJson.error = 0;
rspJson.url = $@"../../upload/" + tempname;
return Json(rspJson);
}
}
public class PicUploadResponse
{
public int error { get; set; }
public string url { get; set; }
}
}
注意這個方法由於是.net core的 所以跟.net framework的有很大區別。
這個代碼如果在文本編輯器裏上傳圖片 會將圖片傳入wwwroot目錄下的upload目錄中
done!
效果如下圖: