Asp.NET使用MarkDown上传图片
电脑版发表于:2020/5/5 15:03
初始化富文本编辑器就不写了,初学者去看这篇文章.NETCore配置MarkDown的学习之路 (一)
前台代码
配置imageUploadURL属性并且调用后台上传图片代码
代码贴出来
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"
});
后台代码
代码不解释 应该能看懂
控制器方法
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);
}
这里处理文件MD5加密
贴代码
public static string CalcMD5(Stream stream)
{
using (MD5 md5 = MD5.Create())
{
byte[] computeBytes = md5.ComputeHash(stream);
string result = "";
for (int i = 0; i < computeBytes.Length; i++)
{
result += computeBytes[i].ToString("X").Length == 1 ? "0" + computeBytes[i].ToString("X") : computeBytes[i].ToString("X");
}
return result;
}
}
看效果吧,步骤太多懒得写 想要研究的下方评论找我要dome代码