CKEdit上传图片报错处理:缺少图像源文件地址
作者:陆金龙
发表时间:2016-07-05 00:38
Asp.Net Mvc项目中,使用CKEdit上传图片报错处理:缺少图像源文件地址。
ckedit下config.js的配置是这样的:
config.filebrowserUploadUrl = "/Ajax/UploadArticleImg.ashx";
一般处理程序代码是的关键代码是这样的:
//context.Response.Write(saveFileName); var CKEditorFuncNum = System.Web.HttpContext.Current.Request["CKEditorFuncNum"]; context.Response.Write("< script>window.parent.CKEDITOR.tools.callFunction(" CKEditorFuncNum ", \"" saveFileName "\",\"\");< / script>");
第一步:如上,根据网上介绍,已将返回结果由返回路径saveFileName改为让客户端执行一段js脚本。
报错处理:缺少图像源文件地址。经查看页面元素,原来只是返回了带script的字符串,脚本并没有执行。于是注意到之前返回文件路径使用的ContentType是text/plain。
第二步:将ContentType改为"text/html"。
//context.Response.ContentType = "text/plain"; context.Response.ContentType = "text/html";
修改之后,使用edge浏览器测试,上传图片完成之后,自动跳转到图片显示和编辑的Tab项。
上传之前和上传之后的界面如下所示。
点击确定后,成功插入到CKEdit编辑窗体中。
但是,后来发现在Chorme浏览器中,还是不成功,仍然报“缺少图像源文件地址的错误”,而且调试中发现,请求根本没有到达服务端。
有网友说是跨域方面的问题,需要添加代码response.SetHeader("X-Frame-Options", "SAMEORIGIN")。
第三步:设置响应头"X-Frame-Options"为"SAMEORIGIN"。
context.Response.AddHeader("X-Frame-Options", "SAMEORIGIN");
设置完成后,问题 果然解决。
服务端的完整代码如下:
public class UploadArticleImg : IHttpHandler { public void ProcessRequest(HttpContext context) { //context.Response.ContentType = "text/plain"; context.Response.ContentType = "text/html";//text/plain会导致script脚本不执行,CKEditor报错:缺少图像源文件地址 context.Response.AddHeader("X-Frame-Options", "SAMEORIGIN");//解决Chrome浏览器报错:缺少图像源文件地址 HttpPostedFile file = context.Request.Files["upload"]; if (file == null) { context.Response.Write("error:nofile"); context.Response.End(); } string filename = Path.GetFileName(file.FileName); //客户端校验是可以被跳过的。所以服务端的第三道防线不能少! string ext = Path.GetExtension(filename);//文件后缀 if (ext == ".jpg" || ext == ".png") { DateTime now = DateTime.Now; string saveDir = "/Upload/Images/" now.Year "/" now.Month "/" now.Day "/"; //得到文件“内容”的MD5值,而不是“文件名”的MD5值 string saveFileName = saveDir Md5Helper.Md5EncryptStream(file.InputStream) ext; string fullPath = context.Server.MapPath("~" saveFileName);//要保存文件在磁盘上的全路径 Directory.CreateDirectory(Path.GetDirectoryName(fullPath));//如果文件夹不存在则创建 file.SaveAs(context.Server.MapPath("~" saveFileName)); //把服务端保存的文件路径返回给客户端 //context.Response.Write(saveFileName); var CKEditorFuncNum = System.Web.HttpContext.Current.Request["CKEditorFuncNum"]; context.Response.Write("< script>window.parent.CKEDITOR.tools.callFunction(" CKEditorFuncNum ", \"" saveFileName "\",\"\");< / script>"); } else { context.Response.Write("error:filetypeerror"); } } public bool IsReusable { get { return false; } } }