在Asp.Net Core中配置使用MarkDown富文本编辑器实现图片上传和截图上传(开源代码.net core3.0)

我们的富文本编辑器不能没有图片上传尤其是截图上传,下面我来教大家怎么实现MarkDown富文本编辑器截图上传和图片上传。

1.配置编辑器到html页

<div id="test-editormd">
        <textarea id="articleContent" style="display: none;">@Html.Raw(Model.Context)</textarea>
    </div>

2.初始化需要配置图片上传

$(function () {
        testEditor = editormd("test-editormd", {
             "99%",
            height: 640,
            syncScrolling: "single",
            path: "/Lib/MarkDown/lib/",
            saveHTMLToTextarea: true,
            emoji: true,
            //图片上传
            imageUpload: true,
            imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
            imageUploadURL: "/Editor/UpImage/@Model.Id"
        });

    });

3.截图上传功能添加

$("#test-editormd").on('paste', function (ev) {
        var items = (event.clipboardData || event.originalEvent.clipboardData).items;
        for (var index in items) {
            var item = items[index];
            if (item.kind === 'file') {
                var blob = item.getAsFile();
                var reader = new FileReader();
                reader.onload = function (event) {
                    //将剪切板中复制信息转换成一种base64格式字符串
                    var base64 = event.target.result;
                        //ajax上传图片
                        $.ajax({
                            url: "/Editor/UpladFilePIC/@Model.Id",
                            type: 'post',
                            data: { 'base': base64},
                            async: false,
                            dataType: 'json',
                            success: function (res) {
                                if(res.code==1)//新一行的图片显示
                                    testEditor.insertValue("
![" + "image.png" + "](" + res.msg + ")");
                            },
                            error: function () {
                                alert('图片上传错误');
                            }
                        });
                    }
                }; // data url!
                var url = reader.readAsDataURL(blob);
            }
    });

4.后台实现图片保存

(1)截图保存

[HttpPost]
        public  string UpladFilePIC(long? id)//id传过来,如需保存可以备用
        {
            IFormCollection fc = HttpContext.Request.Form;
            string savePath = string.Empty;
            int code = 0;
            string msg = "";
            string base64 = fc["base"];
            if (base64 != null)
            {
                string[] spl = base64.Split(',');
                string getImgFormat = spl[0].Split(':')[1].Split('/')[1].Split(';')[0];
                byte[] arr2 = Convert.FromBase64String(spl[1]);
                //上传到服务器
                DateTime today = DateTime.Today;
                string md5 = CommonHelper.CalcMD5(spl[1]);
                string upFileName = md5 + "." + getImgFormat;//生成随机文件名( System.Guid.NewGuid().ToString() )
                var pathStart = ConfigHelper.GetSectionValue("FileMap:ImgPath") + DateTime.Now.Year + "/" + DateTime.Now.Month + "/";
                if (System.IO.Directory.Exists(pathStart) == false)//如果不存在新建
                {
                    System.IO.Directory.CreateDirectory(pathStart);
                }
                var filePath = pathStart + upFileName;
                string pathNew = ConfigHelper.GetSectionValue("FileMap:ImgWeb") + filePath.Replace(ConfigHelper.GetSectionValue("FileMap:ImgPath"), "");
                using (MemoryStream memoryStream = new MemoryStream(arr2, 0, arr2.Length))
                {
                    memoryStream.Write(arr2, 0, arr2.Length);
                    System.DrawingCore.Image image = System.DrawingCore.Image.FromStream(memoryStream);//  转成图片
                    image.Save(filePath);  // 将图片存到本地 
                    code = 1;
                    msg = pathNew;
                }
            }
            string jsonResult = CommonHelper.GetJsonResult(code, msg);
            return jsonResult;
        }

(2)上传保存

public JsonResult UpImage(long? id)//id传过来,如需保存可以备用
        {
            int success = 0;
            string msg = "";
            string pathNew = "";
            try
            {
                var date = Request;
                var files = Request.Form.Files;
                foreach (var formFile in files)
                {
                    if (formFile.Length > 0)
                    {
                        string fileExt = formFile.FileName.Substring(formFile.FileName.LastIndexOf(".") + 1, (formFile.FileName.Length - formFile.FileName.LastIndexOf(".") - 1)); //扩展名
                        long fileSize = formFile.Length; //获得文件大小,以字节为单位
                        string md5 = CommonHelper.CalcMD5(formFile.OpenReadStream());
                        string newFileName = md5 + "." + fileExt; //MD5加密生成文件名保证文件不会重复上传
                        var pathStart = ConfigHelper.GetSectionValue("FileMap:ImgPath") + DateTime.Now.Year + "/" + DateTime.Now.Month + "/";
                        if (System.IO.Directory.Exists(pathStart) == false)//如果不存在新建
                        {
                            System.IO.Directory.CreateDirectory(pathStart);
                        }
                        var filePath = pathStart + newFileName;
                        pathNew = ConfigHelper.GetSectionValue("FileMap:ImgWeb") + filePath.Replace(ConfigHelper.GetSectionValue("FileMap:ImgPath"), "");
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {

                            formFile.CopyTo(stream);
                            success = 1;
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                success = 0;
                msg = ex.ToString();
            }
            var obj = new { success = success, url = pathNew, message = msg };
            return Json(obj);
        }

5.效果图

在Asp.Net Core中配置使用MarkDown富文本编辑器实现图片上传和截图上传(开源代码.net core3.0)在Asp.Net Core中配置使用MarkDown富文本编辑器实现图片上传和截图上传(开源代码.net core3.0)

相关推荐:

1.在Asp.Net或.Net Core中配置使用MarkDown富文本编辑器有开源模板代码(代码是.net core3.0版本)

2.MarkDown富文本编辑器怎么加载模板文件

开源地址 动动小手,点个推荐吧!

注意:我们机遇屋该项目将长期为大家提供asp.net core各种好用demo,旨在帮助.net开发者提升竞争力和开发速度,建议尽早收藏该模板集合项目