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;
            }
        }
    }
}
相关推荐
wearegogog1231 小时前
C# .NET 文件比较工具 WinForms
开发语言·c#·.net
糖不吃1 小时前
WPF值转换器
c#
Popeye-lxw3 小时前
由罗技 K380 键盘 FN 键模式切换引发的血案
c#
FL16238631293 小时前
C# OpenCvSharp 基于霍夫变换直线检测的文本图像倾斜校正文本图像倾斜校
开发语言·c#
aini_lovee4 小时前
C# 快递单打印系统(万能套打系统)
开发语言·c#
白菜上路5 小时前
C# Serilog.AspNetCore基本使用
c#·serilog
小白不白1115 小时前
C# WinForm 与 VP 二次开发
开发语言·c#
SunnyDays10116 小时前
如何使用 C# 自动调整 Excel 行高和列宽
开发语言·c#·excel
itgather7 小时前
OfficeExcel — Word / Excel DLL 验证台功能介绍
c#·word·excel
云中小生7 小时前
Scrutor:.NET 依赖注入自动化的优雅实现
c#·.net