你好,在吗?请问如何在asp ckeditor上传图片?

你好,在吗?请问如何在asp ckeditor上传图片?,第1张

表单中的处理

<li><div id=lititle>店铺介绍</div>

<IFRAME src="/upload/UpLoadPic.asp" frameBorder=0 width=255 scrolling=no height=20></IFRAME>

(图片插入到编辑区光标位置,大小 <%=Def_FileSystem_EnableFileSize/1024%>K,格式: <%=Left(replace(replace(Def_FileSystem_UpLoadFileExt,"|","",1,1),"|","、"),len(replace(replace(Def_FileSystem_UpLoadFileExt,"|","",1,1),"|","、"))-1)%>)

<textarea id="jieshao" name="jieshao" width="98%" HEIGHT="100%"><%=Rs("jieshao")%></textarea>

<script type="text/javascript">

CKEDITOR.replace( 'jieshao' )

function InsertPic(obj){

CKEDITOR.instances.jieshao.insertHtml("<img src='"+obj+"'>")

AddDDDLOption("piclist",obj,obj)

document.getElementById("Tupian1").value = document.getElementById("Tupian1").value +","+ obj

//alert(CKEDITOR.instances.jieshao.getData())

}

</script>

</li>

上传表单文件UpLoadPic.asp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML><HEAD><TITLE>文件上传</TITLE><META http-equiv=Content-Type content="text/htmlcharset=utf-8">

<STYLE type=text/css>

BODY {

MARGIN: 0px

}

INPUT {

BORDER-RIGHT: #666666 1px solidBORDER-TOP: #666666 1px solidFONT-SIZE: 12pxBORDER-LEFT: #666666 1px solidBORDER-BOTTOM: #666666 1px solid

}

.bt1 {

FILTER: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr=#ffffff, EndColorStr=#cecfde)

}

</STYLE>

<META content="MSHTML 6.00.2900.5897" name=GENERATOR></HEAD>

<BODY>

<FORM id=FormDKUP style="MARGIN: 0px" name=FormDKUP action=Uploadpicsave.asp method=post encType=multipart/form-data>

<div>

<INPUT type=file name=DKFile><INPUT class=bt1 type=submit value=" 提交 " name=Submit>

</div>

</FORM>

</BODY></HTML>

上传处理文件Uploadpicsave.asp

我上传使用Persits.Upload上传组件和Persits.Jpeg进行图片处理

<!--#include file="../upload/Config.asp" -->

<!--#include file="../upload/Class_Fun.asp" -->

<%

Dim Def_StrPicMark_Info:Def_StrPicMark_Info="Ly.LFRen.com 廊坊旅游网"

Dim MarkFile

MarkFile=Def_TsysRootPath&Def_FileSystem_DirectoryRoot&"/logo.gif"

Dim Upload

Set Upload = Server.CreateObject("Persits.Upload")

Upload.OverwriteFiles = True

Upload.SetMaxsize Def_FileSystem_EnableFileSize,True

Upload.save() '先将文件保存到内存,改为count=Upload.save()可返回上传文件数量

If err.number=8 Then

Response.write "1文件大小超过限制!"

Response.End()

End if

Dim sql,rs,MyFiles

dim lpid,jianjie

Dim Filepath,LocalFilepath,AddDate

' lpid=Upload.form("lpid").value

' jianjie=trim(Upload.form("addjianjie").value)

For each MyFiles in Upload.Files

'检查图片的扩展名

If InStr(UCase(Def_FileSystem_UpLoadFileExt),"|"&UCase(MyFiles.Ext)&"|")=0 Then

Response.Write("2文件类型不被允许")

Response.End

End If

if MyFiles.Size>Def_FileSystem_EnableFileSize then

response.write "<script type=""text/javascript"" language=""JavaScript"" >"

response.write "alert('3文件大小超过限制')"

response.write "window.location='uploadpic.asp'"

response.write "</script>"

Response.End

end if

'图片上传

AddDate=Now()

Filepath=CreatePicSaveToPath(AddDate,MyFiles.Ext)

LocalFilepath=GetCreatePicLocalPath(AddDate,MyFiles.Ext)

MyFiles.Saveas Filepath

If Def_AddPicMark_Type Then

call CreatePicMark(Filepath,Server.MapPath(MarkFile))

Else

call CreateStrMark(Filepath)

End if

'将上传的图片加入在线编辑器。

response.write "<script type=""text/javascript"" language=""JavaScript"" >"

response.write "window.location='uploadpic.asp'"

response.write "parent.InsertPic('"&LocalFilepath&"')"

response.write "</script>"

'将上传图片地址保存到数据库

' sql="SELECT id,lpid,tupian,jianjie from Tupian "

'response.write sql

' set rs = server.CreateObject ("adodb.recordset")

' rs.Open sql,connhouse , 1, 3

' rs.addnew

' rs("lpid")=lpid

' rs("jianjie")=jianjie

' rs("tupian")=LocalFilepath

' rs.update

' rs.close

' set rs=nothing

' closedb()

Next

Set UpLoad=Nothing

'添加文本水印

Function CreateStrMark(Filepath)

Dim aa,bb,cc

Dim MyJpeg,ToLogo

Dim Jpeg

Set Jpeg = Server.CreateObject("Persits.Jpeg")

If -2147221005=Err then

Response.write "4没有这个组件,请安装!" '检查是否安装AspJpeg组件

Response.End()

End If

Jpeg.Open (Filepath) '打开图片

aa=Jpeg.Binary '将原始数据赋给aa

If err.number then

Response.write"5打开图片aa失败,请检查路径!"

Response.End()

End if

'=========加文字水印,水印字体大小根据重新保存图片尺寸进行调整=================

REM 如果设定图片保存尺寸,将上传的图片长宽尺寸进行调整

If Def_UploadPicWidth>0 and Jpeg.Width>Def_UploadPicWidth Then

Jpeg.Canvas.Font.Size = 66 '字体大小

Jpeg.Canvas.Font.ShadowYOffset = 10

Jpeg.Canvas.Font.ShadowXOffset = 10

Else

Jpeg.Canvas.Font.Size = 36 '字体大小

Jpeg.Canvas.Font.ShadowYOffset = 2

Jpeg.Canvas.Font.ShadowXOffset = 2

End If

Jpeg.Canvas.Font.Color = &Hffffff '水印文字颜色

Jpeg.Canvas.Font.Family = "宋体" '字体

Jpeg.Canvas.Font.Bold = True '是否加粗

Jpeg.Canvas.Font.ShadowColor = &H666666 '阴影色彩

Jpeg.Canvas.Brush.Solid = True

Jpeg.Canvas.Font.Quality = 5 '输出质量

' Jpeg.Canvas.PrintText Jpeg.OriginalWidth/2-100,Jpeg.OriginalHeight/2+20,Def_StrPicMark_Info '水印位置及文字

Jpeg.Canvas.PrintText 20,20,Def_StrPicMark_Info '水印位置及文字

' Jpeg.Canvas.PrintText SrcImg.Width/2-MarkImg.Width/2, SrcImg.height/2-MarkImg.Height/2,,Def_StrPicMark_Info '水印位置及文字

bb=Jpeg.Binary '将文字水印处理后的值赋给bb,这时,文字水印没有不透明度

'============调整文字透明度================

Set MyJpeg = Server.CreateObject("Persits.Jpeg")

MyJpeg.OpenBinary aa

Set ToLogo = Server.CreateObject("Persits.Jpeg")

ToLogo.OpenBinary bb

MyJpeg.DrawImage 0,0, ToLogo, 0.5 '0.3是透明度

cc=MyJpeg.Binary '将最终结果赋值给cc,这时也可以生成目标图片了

' response.BinaryWrite cc '将二进输出给浏览器

REM 如果设定图片保存尺寸,将上传的图片长宽尺寸进行调整

If Def_UploadPicWidth>0 and MyJpeg.Width>Def_UploadPicWidth Then

MyJpeg.Height = CInt(Def_UploadPicWidth * (MyJpeg.Height/MyJpeg.Width))

MyJpeg.Width = Def_UploadPicWidth

End If

MyJpeg.Save (Filepath)

Rem 保存小图

If Def_SmallUploadPicWidth>0 and MyJpeg.Width>Def_SmallUploadPicWidth Then

MyJpeg.Height = CInt(Def_SmallUploadPicWidth * (MyJpeg.Height/MyJpeg.Width))

MyJpeg.Width = Def_SmallUploadPicWidth

MyJpeg.Save (replace(Filepath,left(Filepath,InStr(Filepath,".")-1),left(Filepath,InStr(Filepath,".")-1)&"_S"))

End If

set aa=nothing

set bb=nothing

set cc=nothing

Jpeg.close

MyJpeg.Close

ToLogo.Close

Set Jpeg=Nothing

Set MyJpeg=Nothing

Set ToLogo=Nothing

End Function

'添加图片水印

'Filepath原图(被处理图片) MarkImgPath 小图片(需要附加的小图标,最好是gif得透明图片) SrcImgPath豫览图

Function CreatePicMark(Filepath,MarkImgPath)

REM 读取原图,并准备添加水印。

Dim SrcImg,MarkImg

Dim ImageWidth,ImageHeight

ImageWidth=200

ImageHeight=150

Set SrcImg = Server.CreateObject("Persits.Jpeg")

REM 读取要处理的原文件。

SrcImg.Open Trim(Filepath)

If err.number then

Response.write"5打开图片aa失败,请检查路径!"

Response.End()

End if

If SrcImg.OriginalWidth<Cint(ImageWidth) or SrcImg.Originalheight<Cint(ImageHeight) Then

Set SrcImg = Nothing

Exit Function

Response.write"5打开图片aa失败,请检查路径!"

Response.End()

Else

REM 增加水印后图片的边框色彩。

''SrcImg.Canvas.Pen.Color = &H1EB81E

REM 增加水印后图片的边框宽度。

SrcImg.Canvas.Pen.Width = 0

REM 边框内是否填充颜色

SrcImg.Canvas.Brush.Solid = False

Set MarkImg = Server.CreateObject("Persits.Jpeg")

REM 读取添加的图片。

MarkImg.Open MarkImgPath

REM 处理水印图的大小

If MarkImg.Width >SrcImg.Width Then

MarkImg.Height = CInt(MarkImg.Height * (SrcImg.Width/MarkImg.Width))

MarkImg.Width = SrcImg.Width

End If

If MarkImg.Height >SrcImg.Height Then

MarkImg.Width = CInt(MarkImg.Width * (SrcImg.Height/MarkImg.Height))

MarkImg.Height = SrcImg.Height

End If

REM 如果设定图片保存尺寸,将上传的图片长宽尺寸进行调整

If Def_UploadPicWidth>0 and SrcImg.Width>Def_UploadPicWidth Then

SrcImg.Height = CInt(Def_UploadPicWidth * (SrcImg.Height/SrcImg.Width))

SrcImg.Width = Def_UploadPicWidth

End If

REM 水印图片的起始坐标,0.5是透明度,1表示不透明

SrcImg.DrawImage SrcImg.Width/2-MarkImg.Width/2, SrcImg.height/2-MarkImg.Height/2, MarkImg, 0.8, &HFFFFFF

REM 水印可用的范围。

' SrcImg.Canvas.Bar 0, 0, SrcImg.Width,SrcImg.Height

REM 根据以上参数生成增加水印后的图片文件。

SrcImg.Save Filepath

Rem 保存小图

If Def_SmallUploadPicWidth>0 and SrcImg.Width>Def_SmallUploadPicWidth Then

SrcImg.Height = CInt(Def_SmallUploadPicWidth * (SrcImg.Height/SrcImg.Width))

SrcImg.Width = Def_SmallUploadPicWidth

SrcImg.Save (replace(Filepath,left(Filepath,InStr(Filepath,".")-1),left(Filepath,InStr(Filepath,".")-1)&"_S"))

End If

' SrcImg.Sharpen 1, 120

REM 生成增加水印后的图片的预览图片。

' SrcImg.Save Filepath

End If

Set SrcImg=Nothing

Set MarkImg=Nothing

end Function

%>

CKeditor可以配合CKfinder实现文件的上传及管理。但是往往我们上传的图片需要某些自定义的 *** 作,比如将图片路径写入数据库,图片加水印等等 *** 作。

实现原理:配置CKeditor的自定义图标,单击d出一个子窗口,在在子窗口中上传图片实现我们的自己的功能,然后自动关闭子窗口将图片插入到CKeditor的当前光标位置。

实现步骤:

1、配置CKeditor。网上很多资料,大家自己查。

2、配置config.js文件。此文件为CKeditor的配置文件。配置需要显示的图标。

1 CKEDITOR.editorConfig = function( config )

2 {

3// Define changes to default configuration here. For example:

4config.language = 'zh-cn'

5 config.skin = 'v2'

6// config.uiColor = '#AADC6E'

7config.toolbar =

8 [

9['Source', '-', 'Preview', '-'],

10 ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord'],

11 ['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'],

12 '/',

13 ['Bold', 'Italic', 'Underline'],

14 ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent'],

15 ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],

16 ['Link', 'Unlink', 'Anchor'],

17 ['addpic','Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'],//此处的addpic为我们自定义的图标,非CKeditor提供。

18 '/',

19 ['Styles', 'Format', 'Font', 'FontSize'],

20 ['TextColor', 'BGColor'],

21

22 ]

23

24 config.extraPlugins = 'addpic'

25

26 }

3、在CKeditor\plugins文件夹下新建addpic文件夹,文件夹下添加addpic.JPG图标文件,建议尺寸14*13。addpic.JPG图标文件即为显示在CKeditor上的addpic的图标。在图标文件同目录下添加文件plugin.js,内容如下。

1 (function () {

2//Section 1 : 按下自定义按钮时执行的代码

3var a = {

4 exec: function (editor) {

5 show()

6 }

7 },

8 b = 'addpic'

9 CKEDITOR.plugins.add(b, {

10 init: function (editor) {

11 editor.addCommand(b, a)

12 editor.ui.addButton('addpic', {

13 label: '添加图片',

14 icon: this.path + 'addpic.JPG',

15 command: b

16 })

17 }

18 })

19 })()

文件中的show函数为显示子页面使用,我将它写在CKeditor所在的页面中。

4、edit.aspx页面使用的js

edit.aspx页面就是使用CKeditor的页面。

function show() {

$("#ele6")[0].click()

}

function upimg(str) {

if (str == "undefined" || str == "") {

return

}

str = "<img src='/html/images/" + str+"'</img>"

CKEDITOR.instances.TB_Content.insertHtml(str)

close()

}

function close() {

$("#close6")[0].click()

}

$(document).ready(function () {

new PopupLayer({ trigger: "#ele6", popupBlk: "#blk6", closeBtn: "#close6", useOverlay: true, offsets: { x: 50, y: 0} })

})

以上就是js的代码,d出窗口是使用jquery的d出层,d出层中嵌套iframe,iframe中使用upimg.aspx上传页面,大家如果有其他需要可以自己去设计d出效果。为了大家调试方便,我将我实现d出层的代码贴出来。

d出层效果使用的是popup_layer.js方案,需要进一步加工的朋友可以自己在百度中谷歌。ele6为d出激发需要的层,blk6为d出层主体,close6为层中承载关闭按钮的层。代码如下

<div id="ele6" style="cursor:handcolor: bluedisplay:none"></div>

<div id="blk6" class="blk" style="display:none">

<div class="head"><div class="head-right"></div></div>

<div class="main">

<a href="javascript:void(0)" id="close6" class="closeBtn"></a>

<iframe src="upimg.aspx"></iframe>

</div>

</div>

别忘记引用jquery和popup_layer.js。

5、upimg.aspx页面

aspx代码

<div>

<asp:FileUpload ID="FU_indexIMG" runat="server"/>

<br />

<asp:Button ID="Button1" runat="server" Text="上传" onclick="Button1_Click"/>

<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="取消"/>

</div>

对应的cs代码

1protectedvoid Button1_Click(object sender, EventArgs e)

2 {

3string imgdir = UpImg()

4 script = "window.parent.upimg('" + imgdir + "')"

5 ResponseScript(script)

6 }

7protectedvoid Button2_Click(object sender, EventArgs e)

8 {

9string script = "window.parent.close()"

10 ResponseScript(script)

11 }

12///<summary>

13/// 输出脚本

14///</summary>

15publicvoid ResponseScript(string script)

16 {

17 System.Text.StringBuilder sb = new System.Text.StringBuilder("<script language='javascript' type='text/javascript'>")

18 sb.Append(script)

19 sb.Append("</script>")

20 ClientScript.RegisterStartupScript(this.GetType(), RandomString(1), sb.ToString())

21 }

22///<summary>

23/// 获得随机数

24///</summary>

25///<param name="count">长度</param>

26///<returns></returns>

27publicstaticstring RandomString(int count)

28 {

29 RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()

30byte[] data = newbyte[count]

31 rng.GetBytes(data)

32return BitConverter.ToString(data).Replace("-", "")

33 }

Button1_Click为确定按钮的单击事件函数。其中使用UpImg函数实现上传图片文件,我还在其中实现了加水印,缩图,将图片文件的大小以及相对路径存入数据库等自定义 *** 作,大家可以在此发挥。UpImg返回值为保存图片的相对路径,然后调用editer.aspx页面的js函数upimg。js函数upimg功能为将字符串插入到CKeditor的当前光标位置,插入的是html代码。至此为止带有新上传图片相对路径的img标签就插入CKeditor的编辑区了,能够显示图片了。

Button1_Click为取消按钮的单击事件函数。调用editer.aspx页面的js函数close,将d出层隐藏。

为ckeditor添加图像的方法

1. 到官网下载ckeditor

2. 复制到java web项目目录下

3. 配置config文件,打开图片上传功能

CKEDITOR.editorConfig = function (config) {

// 换行方式

config.enterMode = CKEDITOR.ENTER_BR

// 当输入:shift+Enter是插入的标签

config.shiftEnterMode = CKEDITOR.ENTER_BR//

//图片处理

config.pasteFromWordRemoveStyles = true

config.filebrowserImageUploadUrl = "ckUploadImage.action?type=image"

// 去掉ckeditor“保存”按钮

config.removePlugins = 'save'

}

4. java后台处理代码

// 上传图片

@Action(value = "/ckUploadImage", results = { @Result(name = "success", location = "/upload.jsp") })

public String uploadImages() throws Exception {

HttpServletRequest request = ServletActionContext.getRequest()

FileOutputStream fos

String webRoot = request.getSession().getServletContext().getRealPath(

"")

// 获取图片后缀名

String partRightType = uploadFileName.substring(uploadFileName

.lastIndexOf("."))

String CKEditorFuncNum = request.getParameter("CKEditorFuncNum")

// 判断图片的格式

if (!ImageFile.checkImageType(partRightType)) {

String path = ""

String alt_msg = "Sorry! Image format selection is incorrect, please choose GIF, jpeg, PNG format JPG, picture!"

pringWriterToPage("<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction("

+ CKEditorFuncNum

+ ", '"

+ path

+ "' , '"

+ alt_msg

+ "')</script>")

} else {

try {

uploadFileName = DateUtils.getDateNoStyle() + "-"

+ UUID.randomUUID() + partRightType

String savePath = webRoot + Constants.UPLOAD_IMAGES_PATH

File uploadFilePath = new File(savePath)

if (uploadFilePath.exists() == false) {

uploadFilePath.mkdirs()

System.out.println("路径不存在,但是已经成功创建了" + savePath)

} else {

System.out.println("路径存在了" + savePath)

}

fos = new FileOutputStream(new File(savePath + uploadFileName))

FileInputStream fis = new FileInputStream(getUpload())

byte[] buffer = new byte[1024]

int len = 0

while ((len = fis.read(buffer)) >0) {

fos.write(buffer, 0, len)

}

fos.close()

fis.close()

} catch (FileNotFoundException foe) {

System.out.println("上传文件为0字节")

}

// String path = "http://" + request.getServerName() + ":"

// + request.getServerPort() + request.getContextPath()

// + Constants.UPLOAD_IMAGES_PATH + uploadFileName

String path = request.getContextPath()

+ Constants.UPLOAD_IMAGES_PATH + uploadFileName

String alt_msg = ""

pringWriterToPage("<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction("

+ CKEditorFuncNum

+ ", '"

+ path

+ "' , '"

+ alt_msg

+ "')</script>")

}

return null

}

* 其实重点的代码就是这点

pringWriterToPage("<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction("

+ CKEditorFuncNum

+ ", '"

+ path

+ "' , '"

+ alt_msg

+ "')</script>")


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11553029.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-16
下一篇 2023-05-16

发表评论

登录后才能评论

评论列表(0条)

保存