C#+ckeidtor5实现图片上传

index.html

html 复制代码
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>CkEditor5</title>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
        }

        .editor-container {
            width: 100%;
            height: 100%;
        }

        #editor {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <div class="editor-container">
        <textarea id="editor">
        <p>Hello World!</p>
    </textarea>
    </div>
    <script src="lib/ckeditor.js"></script>
    <script src="lib/translations/zh-cn.js"></script>
    <script>
        ClassicEditor.create(document.querySelector('#editor'), {
            licenseKey: 'GPL',
            language: 'zh-cn',
            simpleUpload: {
            	//同一个域名下可以不写
			    uploadUrl: '/Handler1.ashx',
			},
        })
            .then(editor => {
                window.editor = editor;
            })
            .catch(error => {
                console.error('There was a problem initializing the editor.', error);
            });
    </script>
</body>
</html>

后端接口如下

cs 复制代码
using System.IO;
using System.Linq;
using System.Web;

namespace CkEditorStu02
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {
        public string GetCurrentDomainName()
        {
            // 获取当前请求的协议(HTTP或HTTPS)
            string scheme = HttpContext.Current.Request.Url.Scheme;

            // 获取当前请求的主机名(包括端口号)
            string host = HttpContext.Current.Request.Url.Host;

            // 如果需要,可以在这里添加端口号
            int port = HttpContext.Current.Request.Url.Port;

            // 组合协议和主机名以形成完整的域名
            string domainName = scheme + "://" + host + ":" + port;

            return domainName;
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            context.Response.AppendHeader("Access-Control-Allow-Origin", "*"); // 允许来自任何域的请求
            context.Response.AppendHeader("Access-Control-Allow-Methods", "POST,OPTIONS,GET"); // 允许的请求方法
            context.Response.AppendHeader("Access-Control-Allow-Headers", "Content-Type"); // 允许的请求头

            var files = context.Request.Files;
            if (files == null || files.Count <= 0)
            {
                var result = $"{{\"error\": {{\"message\": \"文件不存在\"}}}}";
                context.Response.Write(result);
                return;
            }
            bool isLarge = false;
            string fileName = "";
            for (int i = 0; i < files.Count; i++)
            {
                var file = files[i];
                //判断文件大小
                //大小限制
                int maxSize = 1 * 1024 * 1024;  //最大是2M(转换为字节)
                if (file.ContentLength > maxSize)
                {
                    context.Response.Write($"{{\"error\": {{\"message\": \"上传文件大小超出限制\"}}}}");
                    return;
                }
                //扩展名限制
                string[] exts = { "image/jpg", "image/jpeg", "image/gif", "image/png" };
                if (!exts.Contains(file.ContentType.ToLower()))
                {
                    context.Response.Write("必须上传图片文件");
                    return;
                }
                fileName = Path.GetFileName(file.FileName);
                file.SaveAs(Path.Combine(context.Server.MapPath("~"), fileName));
                break;
            }
            var res = $"{{\"url\": \"{GetCurrentDomainName()}/{fileName}\"}}";
            //同一个域名下,下面的代码也可以
			//var res = $"{{\"url\": \"/{fileName}\"}}";
            context.Response.Write(res);
            /*
             成功:
            {
                "url": "https://example.com/images/foo.jpg"
            }
            失败:
            {
                "error": {
                    "message": "The image upload failed because the image was too big (max 1.5MB)."
                }
            }
             */
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
相关推荐
冰茶_42 分钟前
.NET MAUI 发展历程:从 Xamarin 到现代跨平台应用开发框架
学习·microsoft·微软·c#·.net·xamarin
The Future is mine2 小时前
C# new Bitmap(32043, 32043, PixelFormat.Format32bppArgb)报错:参数无效,如何将图像分块化处理?
开发语言·c#
Iotfsd9 小时前
.NET写的开源工业物联网网关(IoTGateway)
物联网·c#·.net·dotnet·边缘网关·雾计算·工业物联网智能网关
先生沉默先9 小时前
c#接口_抽象类_多态学习
开发语言·学习·c#
江沉晚呤时9 小时前
深入了解C# List集合及两种常见排序算法:插入排序与堆排序
windows·sql·算法·oracle·c#·排序算法·mybatis
iReachers10 小时前
使用命令行加密混淆C#程序
开发语言·c#
[太阳]8810 小时前
Kafka命令行的使用/Spark-Streaming核心编程(二)
c#·linq
电商api接口开发1 天前
ASP.NET MVC 入门指南
c#·asp.net·mvc
我不是程序猿儿1 天前
[C#]反射的实战应用,实际数据模拟
开发语言·c#
爱编程的鱼1 天前
C# 结构(Struct)
开发语言·人工智能·算法·c#