分享

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

 行者花雕 2020-05-13

我们的富文本编辑器不能没有图片上传尤其是截图上传,下面我来教大家怎么实现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", {
            width: "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("\n![" + "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.效果图

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多