最近有个后台管理系统的项目,需要用到富文本,前端是vue,后端是Asp.net,百度搜了个kindeitor,感觉还不错,废话不多说,直接上重点
vue前端部分代码
1.在vue项目种引入 kindeitor富文本
这里可以直接百度一下,很简单,代码较多,我就不上了,可以参考
https://blog.csdn.net/qq_39953537/article/details/100043354
2.解决富文本编辑器上传图片产生的跨域问题
1找到源文件 kindEditor-all.js
2.搜索 KindEditor.plugin(‘image’, function(K){}
找到这个上传图片的方法
3.找到 uploadbutton.submit();
注释掉,然后在它下面添加
var formData = new FormData();
var file=uploadbutton.fileBox[0].files[0];
formData.append("file",file);
K.ajaxForm(self.options.uploadJson, function(data) {
dialog.hideLoading();
if (data.error==0) {
var html = '<img src="' + self.options.basePath + data.url + '" />';
self.appendHtml(html).hideDialog().focus();
}
},'POST',formData,'json');
formData.append(“file”,file);这里的参数是根据接口决定的,我接口接收参数是 file
3.查找_ajax名称的函数,在此函数的后面新增如下代码:
function _ajaxForm(url, fn, method, param, dataType) {
method = method || 'GET';
dataType = dataType || 'json';
var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if (fn) {
var data = _trim(xhr.responseText);
if (dataType == 'json') {
data = _json(data);
}
fn(data);
}
}
};
xhr.send(param);
}
4.在此函数后面加上如下代码
K.ajaxForm=_ajaxForm;
5.在组件种引用kindeditor
<Editor
id="editor_"
class="editor"
width="100%"
height="500px"
:content="Content"
:loadStyleMode="false"
:value="Content"
@on-content-change="EditorInput"
:uploadJson="ApiUrl + '/api/Files/PostImageFile'" //上传路径
@file-list="FileList"
>
</Editor>
Asp.net后台部分代码
因为kindeditor提供的api文档要求返回格式如下
[HttpPost]
public JsonResult PostImageFile(IFormFile file)
{
var result = new { error = 2, url = "", message = "" };
int userId = 0;
int.TryParse(HttpContext.User.Identity.Name, out userId);
string imageVirtual = AppSetting.GetConfig("ImageVirtual");
if (file != null)
{
try
{
Guid guid = Guid.NewGuid();
string filepath = AppSetting.GetConfig("ConnectionStrings:File");
if (!Directory.Exists(filepath))
{
Directory.CreateDirectory(filepath);
}
//文件名称
string projectFileName = guid + Path.GetExtension(file.FileName);
//if (!Suffix.Contains(Path.GetExtension(file.FileName.ToLower())))
//{
// result.IsSuccess = false;
// result.Message = "文件类型不正确";
// return new JsonResult(result);
//}
//上传的文件的路径
string filePath = filepath + $@"\{projectFileName}";
using (FileStream fs = System.IO.File.Create(filePath))
{
file.CopyTo(fs);
fs.Flush();
}
result = new
{
error = 0,
url = string.Format("{0}/{1}", imageVirtual, projectFileName),
message = ""
};
}
catch (System.Exception ex)
{
result = new
{
error = 0,
url = "",
message = ex.Message
};
}
}
return new JsonResult(result);
}
最后看看效果