600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 富文本编辑器 CKeditor 配置使用+上传图片

富文本编辑器 CKeditor 配置使用+上传图片

时间:2023-06-14 20:45:55

相关推荐

富文本编辑器 CKeditor 配置使用+上传图片

参考文献:

富文本编辑器 CKeditor 配置使用

CKEditor与CKFinder的配置(环境),老版本可以参考

CKEditor+CKFinder ASP版在本地电脑中的配置 有点问题

富文本文件CKEDITOR增加上传图片功能(.net),ckeditor上传图片 发现可行

CKEditor4.6.2 图片/Flash上传及预览 附件上传有一定参考价值

富文本编辑器 CKeditor 配置使用+上传图片

Ckeditor下载地址:/download

下载后默认放在网站根目录下ckeditor文件夹中

一、使用方法:

1、在页面<head>中引入ckeditor核心文件ckeditor.js

<script type="text/javascript" src="ckeditor/ckeditor.js"></script>

2、在使用编辑器的地方插入HTML控件<textarea>

<textarea id="TextArea1" cols="20" rows="2" class="ckeditor"></textarea>

如果是环境,也可用服务器端控件<TextBox>

<asp:TextBox ID="tbContent" runat="server" TextMode="MultiLine" class="ckeditor"></asp:TextBox>

注意在控件中加上 class="ckeditor" 。

3、将相应的控件替换成编辑器代码

<script type="text/javascript">CKEDITOR.replace('TextArea1');//如果是在环境下用的服务器端控 件<TextBox>CKEDITOR.replace('tbContent');//如 果<TextBox>控件在母版页中,要这样写CKEDITOR.replace('<%=tbContent.ClientID.Replace("_","$") %>');</script>

4、配置编辑器

ckeditor的配置都集中在 ckeditor/config.js 文件中,下面是一些常用的配置参数:

// 界面语言,默认为 'en'config.language = 'zh-cn';// 设置宽高config.width = 400;config.height = 400;// 编辑器样式,有三种:'kama'(默认)、'office'、'v2'config.skin = 'v2';// 背景颜色config.uiColor = '#FFF';// 工具栏(基础'Basic'、全能'Full'、自定义)plugins/toolbar/plugin.jsconfig.toolbar = 'Basic';config.toolbar = 'Full';这将配合:config.toolbar_Full = [['Source','-','Save','NewPage','Preview','-','Templates'],['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],'/',['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],['Link','Unlink','Anchor'],['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],'/',['Styles','Format','Font','FontSize'],['TextColor','BGColor']];//工具栏是否可以被收缩config.toolbarCanCollapse = true;//工具栏的位置config.toolbarLocation = 'top';//可选:bottom//工具栏默认是否展开config.toolbarStartupExpanded = true;// 取消 “拖拽以改变尺寸”功能 plugins/resize/plugin.jsconfig.resize_enabled = false;//改变大小的最大高度config.resize_maxHeight = 3000;//改变大小的最大宽度config.resize_maxWidth = 3000;//改变大小的最小高度config.resize_minHeight = 250;//改变大小的最小宽度config.resize_minWidth = 750;// 当提交包含有此编辑器的表单时,是否自动更新元素内的数据config.autoUpdateElement = true;// 设置是使用绝对目录还是相对目录,为空为相对目录config.baseHref = ''// 编辑器的z-index值config.baseFloatZIndex = 10000;//设置快捷键config.keystrokes = [[ CKEDITOR.ALT + 121 /*F10*/, 'toolbarFocus' ], //获取焦点[ CKEDITOR.ALT + 122 /*F11*/, 'elementsPathFocus' ], //元素焦点[ CKEDITOR.SHIFT + 121 /*F10*/, 'contextMenu' ], //文本菜单[ CKEDITOR.CTRL + 90 /*Z*/, 'undo' ], //撤销[ CKEDITOR.CTRL + 89 /*Y*/, 'redo' ], //重做[ CKEDITOR.CTRL + CKEDITOR.SHIFT + 90 /*Z*/, 'redo' ], // [ CKEDITOR.CTRL + 76 /*L*/, 'link' ], //链接[ CKEDITOR.CTRL + 66 /*B*/, 'bold' ], //粗体[ CKEDITOR.CTRL + 73 /*I*/, 'italic' ], //斜体[ CKEDITOR.CTRL + 85 /*U*/, 'underline' ], //下划线[ CKEDITOR.ALT + 109 /*-*/, 'toolbarCollapse' ]]//设置快捷键 可能与浏览器快捷键冲突 plugins/keystrokes/plugin.js.config.blockedKeystrokes = [CKEDITOR.CTRL + 66 /*B*/,CKEDITOR.CTRL + 73 /*I*/,CKEDITOR.CTRL + 85 /*U*/]//设置编辑内元素的背景色的取值 plugins/colorbutton/plugin.js.config.colorButton_backStyle = {element : 'span',styles : { 'background-color' : '#(color)' }}//设置前景色的取值 plugins/colorbutton/plugin.jsconfig.colorButton_colors = '000,800000,8B4513,2F4F4F,008080,000080,4B0082,696969,B22222,A52A2A,DAA520,006400,40E0D0,0000CD,800080,808080,F00,FF8C00,FFD700,008000,0FF,00F,EE82EE,A9A9A9,FFA07A,FFA500,FFFF00,00FF00,AFEEEE,ADD8E6,DDA0DD,D3D3D3,FFF0F5,FAEBD7,FFFFE0,F0FFF0,F0FFFF,F0F8FF,E6E6FA,FFF’//是否在选择颜色时显示“其它颜色”选项 plugins/colorbutton/plugin.jsconfig.colorButton_enableMore = false//区块的前景色默认值设置 plugins/colorbutton/plugin.jsconfig.colorButton_foreStyle = {element : 'span',styles : { 'color' : '#(color)' }};//所需要添加的CSS文件 在此添加 可使用相对路径和网站的绝对路径config.contentsCss = './contents.css';//文字方向config.contentsLangDirection = 'rtl'; //从左到右//CKeditor的配置文件 若不想配置 留空即可CKEDITOR.replace( 'myfiled', { customConfig : './config.js' } );//界面编辑框的背景色 plugins/dialog/plugin.jsconfig.dialog_backgroundCoverColor = '#fffefd'; //可设置参考config.dialog_backgroundCoverColor = 'white' //默认//背景的不透明度 数值应该在:0.0~1.0 之间 plugins/dialog/plugin.jsconfig.dialog_backgroundCoverOpacity = 0.5//移动或者改变元素时 边框的吸附距离 单位:像素 plugins/dialog/plugin.jsconfig.dialog_magnetDistance = 20;//是否拒绝本地拼写检查和提示 默认为拒绝 目前仅firefox和safari支持 plugins/wysiwygarea/plugin.js.config.disableNativeSpellChecker = true//进行表格编辑功能 如:添加行或列 目前仅firefox支持 plugins/wysiwygarea/plugin.jsconfig.disableNativeTableHandles = true; //默认为不开启//是否开启 图片和表格 的改变大小的功能 config.disableObjectResizing = true;config.disableObjectResizing = false //默认为开启//设置HTML文档类型config.docType = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd%22' ;//是否对编辑区域进行渲染 plugins/editingblock/plugin.jsconfig.editingBlock = true;//编辑器中回车产生的标签config.enterMode = CKEDITOR.ENTER_P; //可选:CKEDITOR.ENTER_BR或CKEDITOR.ENTER_DIV//是否使用HTML实体进行输出 plugins/entities/plugin.jsconfig.entities = true;//定义更多的实体 plugins/entities/plugin.jsconfig.entities_additional = '#39'; //其中#代替了&//是否转换一些难以显示的字符为相应的HTML字符 plugins/entities/plugin.jsconfig.entities_greek = true;//是否转换一些拉丁字符为HTML plugins/entities/plugin.jsconfig.entities_latin = true;//是否转换一些特殊字符为ASCII字符 如"This is Chinese: 汉语."转换为"This is Chinese: 汉语." plugins/entities/plugin.jsconfig.entities_processNumerical = false;//添加新组件config.extraPlugins = 'myplugin'; //非默认 仅示例//使用搜索时的高亮色 plugins/find/plugin.jsconfig.find_highlight = {element : 'span',styles : { 'background-color' : '#ff0', 'color' : '#00f' }};//默认的字体名 plugins/font/plugin.jsconfig.font_defaultLabel = 'Arial';//字体编辑时的字符集 可以添加常用的中文字符:宋体、楷体、黑体等 plugins/font/plugin.jsconfig.font_names = 'Arial;Times New Roman;Verdana';//文字的默认式样 plugins/font/plugin.jsconfig.font_style = {element : 'span',styles : { 'font-family' : '#(family)' },overrides : [ { element : 'font', attributes : { 'face' : null } } ]};//字体默认大小 plugins/font/plugin.jsconfig.fontSize_defaultLabel = '12px';//字体编辑时可选的字体大小 plugins/font/plugin.jsconfig.fontSize_sizes ='8/8px;9/9px;10/10px;11/11px;12/12px;14/14px;16/16px;18/18px;20/20px;22/22px;24/24px;26/26px;28/28px;36/36px;48/48px;72/72px'//设置字体大小时 使用的式样 plugins/font/plugin.jsconfig.fontSize_style = {element : 'span',styles : { 'font-size' : '#(size)' },overrides : [ { element : 'font', attributes : { 'size' : null } } ]};//是否强制复制来的内容去除格式 plugins/pastetext/plugin.jsconfig.forcePasteAsPlainText =false //不去除//是否强制用“&”来代替“&amp;”plugins/htmldataprocessor/plugin.jsconfig.forceSimpleAmpersand = false;//对address标签进行格式化 plugins/format/plugin.jsconfig.format_address = { element : 'address', attributes : { class : 'styledAddress' } };//对DIV标签自动进行格式化 plugins/format/plugin.jsconfig.format_div = { element : 'div', attributes : { class : 'normalDiv' } };//对H1标签自动进行格式化 plugins/format/plugin.jsconfig.format_h1 = { element : 'h1', attributes : { class : 'contentTitle1' } };//对H2标签自动进行格式化 plugins/format/plugin.jsconfig.format_h2 = { element : 'h2', attributes : { class : 'contentTitle2' } };//对H3标签自动进行格式化 plugins/format/plugin.jsconfig.format_h1 = { element : 'h3', attributes : { class : 'contentTitle3' } };//对H4标签自动进行格式化 plugins/format/plugin.jsconfig.format_h1 = { element : 'h4', attributes : { class : 'contentTitle4' } };//对H5标签自动进行格式化 plugins/format/plugin.jsconfig.format_h1 = { element : 'h5', attributes : { class : 'contentTitle5' } };//对H6标签自动进行格式化 plugins/format/plugin.jsconfig.format_h1 = { element : 'h6', attributes : { class : 'contentTitle6' } };//对P标签自动进行格式化 plugins/format/plugin.jsconfig.format_p = { element : 'p', attributes : { class : 'normalPara' } };//对PRE标签自动进行格式化 plugins/format/plugin.jsconfig.format_pre = { element : 'pre', attributes : { class : 'code' } };//用分号分隔的标签名字 在工具栏上显示 plugins/format/plugin.jsconfig.format_tags = 'p;h1;h2;h3;h4;h5;h6;pre;address;div';//是否使用完整的html编辑模式 如使用,其源码将包含:<html><body></body></html>等标签config.fullPage = false;//是否忽略段落中的空字符 若不忽略 则字符将以“”表示 plugins/wysiwygarea/plugin.jsconfig.ignoreEmptyParagraph = true;//在清除图片属性框中的链接属性时 是否同时清除两边的<a>标签 plugins/image/plugin.jsconfig.image_removeLinkByEmptyURL = true;//一组用逗号分隔的标签名称,显示在左下角的层次嵌套中 plugins/menu/plugin.js.config.menu_groups ='clipboard,form,tablecell,tablecellproperties,tablerow,tablecolumn,table,anchor,link,image,flash,checkbox,radio,textfield,hiddenfield,imagebutton,button,select,textarea';//显示子菜单时的延迟,单位:ms plugins/menu/plugin.jsconfig.menu_subMenuDelay = 400;//当执行“新建”命令时,编辑器中的内容 plugins/newpage/plugin.jsconfig.newpage_html = '';//当从word里复制文字进来时,是否进行文字的格式化去除 plugins/pastefromword/plugin.jsconfig.pasteFromWordIgnoreFontFace = true; //默认为忽略格式//是否使用<h1><h2>等标签修饰或者代替从word文档中粘贴过来的内容 plugins/pastefromword/plugin.jsconfig.pasteFromWordKeepsStructure = false;//从word中粘贴内容时是否移除格式 plugins/pastefromword/plugin.jsconfig.pasteFromWordRemoveStyle = false;//对应后台语言的类型来对输出的HTML内容进行格式化,默认为空config.protectedSource.push( /<"?["s"S]*?"?>/g ); // PHP Codeconfig.protectedSource.push( //g ); // ASP Codeconfig.protectedSource.push( /(]+>["s|"S]*?<"/asp:[^">]+>)|(]+"/>)/gi ); // Code//当输入:shift+Enter时插入的标签config.shiftEnterMode = CKEDITOR.ENTER_P; //可选:CKEDITOR.ENTER_BR或CKEDITOR.ENTER_DIV//可选的表情替代字符 plugins/smiley/plugin.js.config.smiley_descriptions = [':)', ':(', ';)', ':D', ':/', ':P','', '', '', '', '', '','', ';(', '', '', '', '','', ':kiss', '' ];//对应的表情图片 plugins/smiley/plugin.jsconfig.smiley_images = ['regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif','embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif','devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif','broken_heart.gif','kiss.gif','envelope.gif'];//表情的地址 plugins/smiley/plugin.jsconfig.smiley_path = 'plugins/smiley/images/';//页面载入时,编辑框是否立即获得焦点 plugins/editingblock/plugin.js plugins/editingblock/plugin.js.config.startupFocus = false;//载入时,以何种方式编辑 源码和所见即所得 "source"和"wysiwyg" plugins/editingblock/plugin.js.config.startupMode ='wysiwyg';//载入时,是否显示框体的边框 plugins/showblocks/plugin.jsconfig.startupOutlineBlocks = false;//是否载入样式文件 plugins/stylescombo/plugin.js.config.stylesCombo_stylesSet = 'default';//以下为可选config.stylesCombo_stylesSet = 'mystyles';config.stylesCombo_stylesSet = 'mystyles:/editorstyles/styles.js';config.stylesCombo_stylesSet = 'mystyles:/editorstyles/styles.js';//起始的索引值config.tabIndex = 0;//当用户键入TAB时,编辑器走过的空格数,(&nbsp;) 当值为0时,焦点将移出编辑框 plugins/tab/plugin.jsconfig.tabSpaces = 0;//默认使用的模板 plugins/templates/plugin.js.config.templates = 'default';//用逗号分隔的模板文件plugins/templates/plugin.js.config.templates_files = [ 'plugins/templates/templates/default.js' ]//当使用模板时,“编辑内容将被替换”框是否选中 plugins/templates/plugin.jsconfig.templates_replaceContent = true;//主题config.theme = 'default';//撤销的记录步数 plugins/undo/plugin.jsconfig.undoStackSize =20;// 在 CKEditor 中集成 CKFinder,注意 ckfinder 的路径选择要正确。//CKFinder.SetupCKEditor(null, '/ckfinder/');

二、 一些使用技巧

1、在页面中即时设置编辑器

<script type="text/javascript">// 示例1:设置工具栏为基本工具栏,高度为70CKEDITOR.replace('<%=tbLink.ClientID.Replace("_","$") %>',{ toolbar:'Basic', height:70 });//示例2:工具栏为自定义类型CKEDITOR.replace( 'editor1',{toolbar :[//加粗斜体,下划线穿过线下标字 上标字['Bold','Italic','Underline','Strike','Subscript','Superscript'],// 数字列表实体列表 减小缩进 增大缩进['NumberedList','BulletedList','-','Outdent','Indent'],//左对 齐 居中对齐右对齐两端对齐['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],//超链接 取消超链接 锚点['Link','Unlink','Anchor'],//图片 flash 表格 水平线 表情 特殊字符 分页符['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],'/',// 样式 格式字体 字体大小['Styles','Format','Font','FontSize'],//文本颜色背景颜色['TextColor','BGColor'],//全屏 显示区块['Maximize', 'ShowBlocks','-']]});</script>

三、精简ckeditor

在部署到Web服务器上时,下列文件夹和文件都可以删除:

/_samples :示例文件夹;

/_source :未压缩源程序;

/lang文件夹下除 zh-cn.js、en.js 以外的文件(也可以根据需要保留其他语言文件);

根目录下的 changes.html(更新列表),install.html(安装指向),license.html(使用许可);

/skins 目录下不需要的皮肤,一般用V2(简单,朴素) ,如果只保留V2则必须在config.js中指定皮肤。

四, 版本问题

在CKEditor的官方网站上下载,最要下载全部功能,最后得到的压缩包是ckeditor_4.1.1_full.zip,如果选择simple或者standed,可能会有些功能不能用,比如字体颜色,背景颜色,这下功能在standed版本里面就不支持。所以你会很奇怪明明设置了['TextColor','BGColor'],但是文本颜色和背景颜色选项就是不显示。

五,去掉默认的段落标记

去除CKEditor自动添加的<p></p>标签的方法,其实很简单,有两种办法:

1.在ckeditor目录下的config.js添加以下配置参数即可:

config.enterMode = CKEDITOR.ENTER_BR: 屏蔽换行符<br>config.shiftEnterMode = CKEDITOR.ENTER_P:屏蔽段落<p>

2.直接更改编辑器默认模式为源代码模式,在ckeditor目录下的config.js添加以下配置:

config.startupMode = 'source';

六,和kcfinder搭配使用实现图片上传

老版本可以参考:CKEditor与CKFinder的配置(环境),

但是实际应用发现不行,新版本已经发生改变。

后来参考:CKEditor+CKFinder ASP版在本地电脑中的配置发现也不行,设置如下:

第四步配置CKEditor下的config.js文件:下面的路径都要带上根目录(zhongyuan);config.filebrowserBrowseUrl = '/zhongyuan/ckfinder/ckfinder.html';config.filebrowserImageBrowseUrl = '/zhongyuan/ckfinder/ckfinder.html?Type=Images';config.filebrowserFlashBrowseUrl = '/zhongyuan/ckfinder/ckfinder.html?Type=Flash';config.filebrowserUploadUrl = '/zhongyuan/ckfinder/core/connector/asp/connector.asp?command=QuickUpload&type=Files';config.filebrowserImageUploadUrl = '/zhongyuan/ckfinder/core/connector/asp/connector.asp?command=QuickUpload&type=Images';config.filebrowserFlashUploadUrl = '/zhongyuan/ckfinder/core/connector/asp/connector.asp?command=QuickUpload&type=Flash';//此代码为启用上传图片的功能

但是下载的CKFinder 根本就没有core目录,提示找不到文件:无语!这个要收费!好吧!再想办法!

参考:富文本文件CKEDITOR增加上传图片功能(.net),ckeditor上传图片 发现可行!

七、CKEDITOR增加上传图片功能(.net)

第一种方法使用CKEDITOR自身代码功能

“预览”中有一大堆鸟语,看得很不爽。可以使用1或2来进行清除。

1:可以打开ckeditor/plugins/image/dialogs/image.js文件,搜索“b.config.image_previewText”就能找到这段鸟语了,(b.config.image_previewText||'')单引号中的内容全删了,注意别删多了。

2:打开ckeditor/config.js文件,在此函数内,添加

config.image_previewText = ''; //清空预览区域显示内容

打开ckeditor/plugins/image/dialogs/image.js文件,搜索“upload”可以找到这一段

id:'Upload',hidden:true

实际上上传功能被隐藏了,把上面的true改成false,如果你的显示是hidden:!0,直接改成0即可,就可以显示了,再打开编辑器,就能找到上传功能了。

设置上传到服务器按钮的事件URL,指定将上传的文件提交给那个URL进行处理,

打开ckeditor/config.js文件,在此函数内,添加

config.filebrowserImageUploadUrl = '../UploadImgHandler.ashx';//设置提交上传图片按钮处理URL,我这里设置的提交给一个一般处理程序,这个是自己要创建的,我的是创建到根目录的,所以会有../,好了,下面开始编写UploadImgHandler.ashx'文件内的代码吧,如下:

public void ProcessRequest(HttpContext context){String callback = context.Request.QueryString["CKEditorFuncNum"].ToString();///'遍历File表单元素HttpFileCollection files = HttpContext.Current.Request.Files;for (int iFile = 0; iFile < files.Count; iFile++){// ///'检查文件扩展名字HttpPostedFile postedFile = files[iFile];//HttpPostedFile postedFile = files[0];string fileName; //, fileExtensionfileName = System.IO.Path.GetFileName(postedFile.FileName);string fileContentType = postedFile.ContentType.ToString();if (fileContentType == "image/bmp" || fileContentType == "image/gif" ||fileContentType == "image/png" || fileContentType == "image/x-png" || fileContentType == "image/jpeg"|| fileContentType == "image/pjpeg"){if (postedFile.ContentLength <= 2097152){string filepath = postedFile.FileName;//得到的是文件的完整路径,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg //string filepath = FileUpload1.FileName;//得到上传的文件名20022775_m.jpg string serverpath = context.Server.MapPath("~/UpLoadFile/ImageUpload/") + fileName;//取得文件在服务器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg postedFile.SaveAs(serverpath);//上传图片到服务器指定地址string imageurl = "http://localhost:13392/UpLoadFile/ImageUpload/" + fileName;//我是将测试时的本地地址+放置图像的文件夹+图片名称作为返回的URL// 返回"图像"选项卡并显示图片 context.Response.Write("<script type=\"text/javascript\">");context.Response.Write("window.parent.CKEDITOR.tools.callFunction(" + callback+ ",'" + imageurl + "','')");context.Response.Write("</script>");}else{context.Response.Write("<script>alert('上传文件不能大于2M!')</script>");}}else{context.Response.Write("<script>alert('只支持BMP、GIF、JPG、PNG格式的图片!')</script>");}}}

好了,可以上传图片了!哈哈!剩下的方法还没有实验,保留下来,留待研究!

好了,以上是使用CKEDITOR自身的上传功能,外加一个一般处理程序来完成上传功能。

第二种设置上传功能方法:如果你已经有了自己的上传模板(我指的是一个单独的上传网页),

打开ckeditor/plugins/image/dialogs/image.js文件,搜索“urlMissing”可以找到这一段,在},之后添加如下代码:

{ type: 'button', id: 'myUpload', style:"margin-top:14px;", align: 'center', label: '本地上传', onClick: function () { var retFile = showModalDialog("../UpLoadWeixinImg.aspx", "", "dialogHeight:380;dialogWidth:600;"); if (retFile != null) { this.getDialog().setValueOf('info', 'txtUrl', retFile); } } },

showModalDialog("../UpLoadWeixinImg.aspx",指定转向URL的链接地址,上传模板,showModalDialog方法在IE和火狐下能正常运行,在谷歌浏览器下可能不兼容,反正我试了不行,听说用window.open可以代替,我没有去尝试,您可以去试下,

下面来看看UpLoadWeixinImg.aspx上传页面模板的代码如下:

/// <summary>/// 上传图片/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void LinkBtnFileUploadImg_Click(object sender, EventArgs e){if (this.FileUploadImg.HasFile){string fileContentType = FileUploadImg.PostedFile.ContentType;if (fileContentType == "image/bmp" || fileContentType == "image/gif"||fileContentType == "image/png"|| fileContentType == "image/x-png"|| fileContentType == "image/jpeg"|| fileContentType == "image/pjpeg"){int fileSize = this.FileUploadImg.PostedFile.ContentLength;if (fileSize <= 2097152){string fileName = this.FileUploadImg.PostedFile.FileName; // 客户端文件路径string imageurl = "http://localhost:8665/WeiXinImg/" + fileName;string filepath = FileUploadImg.PostedFile.FileName; //得到的是文件的完整路径,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg //string filepath = FileUpload1.FileName;//得到上传的文件名20022775_m.jpg string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg string serverpath = Server.MapPath("~/WeiXinImg/") + filename;//取得文件在服务器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg this.FileUploadImg.PostedFile.SaveAs(serverpath);//将上传的文件另存为//此处我调用的是前台客户端的js脚本ClientScript.RegisterStartupScript(this.GetType(), "SayHello", "<script>SayHello('" + imageurl + "')</script>");}else{Response.Write("<script>alert('上传文件不能大于2M!')</script>");}}else{Response.Write("<script>alert('只支持BMP、GIF、JPG、PNG格式的图片!')</script>");}}else{Response.Write("<script>alert('请选择图片!')</script>");}}SayHello脚本如下:<script type="text/javascript">function SayHello(imgPath) {window.returnValue = imgPath; //上传后的图片链接 window.close();}</script>

两种方式实现方式一样,具体哪个好用可以根据需要选择!

我的最终实现代码如下:

<%@ WebHandler Language="C#" Class="UploadImgHandler" %>using System;using System.Web;public class UploadImgHandler : IHttpHandler {//public void ProcessRequest (HttpContext context) {// context.Response.ContentType = "text/plain";// context.Response.Write("Hello World");//}public bool IsReusable {get {return false;}}public void ProcessRequest(HttpContext context){String callback = context.Request.QueryString["CKEditorFuncNum"].ToString();///'遍历File表单元素HttpFileCollection files = HttpContext.Current.Request.Files;for (int iFile = 0; iFile < files.Count; iFile++){// ///'检查文件扩展名字HttpPostedFile postedFile = files[iFile];//HttpPostedFile postedFile = files[0];string fileName; //, fileExtensionfileName = System.IO.Path.GetFileName(postedFile.FileName);string fileContentType = postedFile.ContentType.ToString();if (fileContentType == "image/bmp" || fileContentType == "image/gif" ||fileContentType == "image/png" || fileContentType == "image/x-png" || fileContentType == "image/jpeg"|| fileContentType == "image/pjpeg"){if (postedFile.ContentLength <= 2097152){string filepath = postedFile.FileName;//得到的是文件的完整路径,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg //string filepath = FileUpload1.FileName;//得到上传的文件名20022775_m.jpg string serverpath = context.Server.MapPath("~/UpLoadFile/ImageUpload/") + fileName;//取得文件在服务器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg postedFile.SaveAs(serverpath);//上传图片到服务器指定地址int iEnd = HttpContext.Current.Request.Url.ToString().IndexOf("PlugIns");//获取当前服务器的 地址和端口string strServerIP = HttpContext.Current.Request.Url.ToString().Substring(0, iEnd);//获取当前服务器的 地址和端口 http://localhost:13392/string imageurl = strServerIP + "UpLoadFile/ImageUpload/" + fileName;//我是将测试时的本地地址+放置图像的文件夹+图片名称作为返回的URL// 返回"图像"选项卡并显示图片 context.Response.Write("<script type=\"text/javascript\">");context.Response.Write("window.parent.CKEDITOR.tools.callFunction(" + callback+ ",'" + imageurl + "','')");context.Response.Write("</script>");}else{context.Response.Write("<script>alert('上传文件不能大于2M!')</script>");}}else{context.Response.Write("<script>alert('只支持BMP、GIF、JPG、PNG格式的图片!')</script>");}}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。