.net layui富文本编辑器上传图片并回显
网上资源,没一个全的。自己整理了下。
引用JS和CSS
<link href="/JS/layui/css/layui.css" rel="stylesheet" />
<link rel="stylesheet" href="/layuiadmin/style/admin.css" />
<script src="/JS/jquery-3.4.1.js"></script>
<script src="/layuiadmin/layui/layui.js"></script>
页面HMTL
<body>
<div style="width:90%;margin-left:5%;margin-top:100px;background-color:#fff;">
<textarea id="txt" style="display:none;"></textarea>
</div>
<input type="button" value="获取内容" id="btn1" class="layui-btn" style="margin-left:5%;margin-top:20px;" />
<script type="text/javascript">
window.onload = function () {
layui.use('layedit', function () {
var layedit = layui.layedit;
layedit.set({
uploadImage: {
url: 'layeditUPIMG.ashx' //接口url。这里试了几次,把接口放二级目录不行
, type: 'post' //默认post
}
});
var editIndex = layedit.build('txt', {
height: 400
});
document.getElementById('btn1').onclick = function () {
alert(layedit.getContent(editIndex));
}
});
}
</script>
</body>
一般处理程序layeditUPIMG。和页面同目录。你也可以试下不同目录,我这是不同目录调不到接口
using Common;
using DAL;
using FastJSON;
using Model;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace MyProject
{
/// <summary>
/// layeditUPIMG 的摘要说明
/// </summary>
public class layeditUPIMG : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string strResult = "{\"code\": 1,\"msg\": \"出现错误\",\"data\": {\"src\": \"\"}}";
var file = context.Request.Files[0]; //获取选中文件
Stream stream = file.InputStream; //将文件转为流
Image img = Image.FromStream(stream);//将流中的图片转换为Image图片对象
//路径映射为绝对路径
//string path = context.Server.MapPath(serverPath);
string strRand = PublicHelper.RanStr(10, true);
string path = context.Server.MapPath("/");//获取网站的根路径
string filePath = "UploadFile\\" + DateTime.Now.ToString("yyyyMMdd") + strRand + ".jpg";//用来存图片的物理路径
string filePath01 = "\\UploadFile\\" + DateTime.Now.ToString("yyyyMMdd") + strRand + ".jpg";//用来回显在编辑器里用的图片路径
string strPath = path + filePath;
try
{
if (!Directory.Exists(path + "UploadFile\\"))
Directory.CreateDirectory(path + "UploadFile\\");
img.Save(strPath, ImageFormat.Jpeg);//图片保存,JPEG格式图片较小
//保存成功后的json
//filePath01.Replace,这里要注意,一定要把\换成/
strResult = "{\"code\": 0,\"msg\": \"成功\",\"data\": {\"src\": \"" + filePath01.Replace("\\","/") + "\",\"title\": \"" + strRand + ".jpg\"}}";
}
catch (Exception ex)
{
string str01 = ex.Message.ToString();
}
context.Response.Write(strResult);//输出结果
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
有疑问随时欢迎提意见

浙公网安备 33010602011771号