CKEditor 3.1 Asp.net下 整合 jQuery.AjaxUpload 实现 图片的上传

1.下载 jQuery 1.3.2

2.下载 ajaxUpload 插件 http://valums.com/ajax-upload/

3.下载 CKEDITOR 3.1

4.准备 接受图片的HttpHandler

using System;
using System.Web;
using System.IO;
using System.Text;
using System.Drawing;
using Feebool.UtilBox;
using System.Web.SessionState;
using System.Drawing.Imaging;

namespace QJService
{
    public class UpImage : IHttpHandler, IRequiresSessionState
    {
        private string ImageFolder = System.Web.Configuration.WebConfigurationManager.AppSettings["UploadFileFolder"];

        public void ProcessRequest(HttpContext context)
        {
            //验证上传的权限
            //------功能暂留
            if (!string.IsNullOrEmpty(ImageFolder))
            {
                context.Response.ContentType = "text/plain";
                context.Response.ContentEncoding = Encoding.UTF8;
                string imageName = "";
                string error = "";
                if (context.Request.Files.Count > 0)
                {
                    try
                    {
                        if (context.Request.Files[0].ContentLength >= 3145728)
                        {
                            throw new Exception("文件超过可上传文件大小!");
                        }

                        if (!string.IsNullOrEmpty(HttpContext.Current.Request["imageFolder"]))
                        {
                            ImageFolder = ImageFolder + HttpContext.Current.Request["imageFolder"] + "/";
                        }

                        //检查目录
                        DirectoryInfo directoryInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath((ImageFolder)));
                        if (!directoryInfo.Exists)
                        {
                            directoryInfo.Create();
                        }

                        string fileName = GetID() + "." + GetExt(context.Request.Files[0].FileName);
                        string filePath = HttpContext.Current.Server.MapPath(ImageFolder + fileName);

                        bool isImageConvert = ConvertTool.ToBoolean(HttpContext.Current.Request["IsImageConvert"]);

                         if (!isImageConvert)
                         {
                             //保存原图
                             context.Request.Files[0].SaveAs(filePath);
                         }
                         else
                         {
                             if (ConvertTool.ToInt(HttpContext.Current.Request["width"]) == 0 &&
                                 ConvertTool.ToInt(HttpContext.Current.Request["height"]) == 0)
                             {
                                 //保存原图
                                 context.Request.Files[0].SaveAs(filePath);
                             }
                             else
                             {
                                 //保存缩图
                                 DrawSmallImage(context.Request.Files[0],
                                     ConvertTool.ToInt(HttpContext.Current.Request["width"]),
                                     ConvertTool.ToInt(HttpContext.Current.Request["height"]), filePath);
                             }
                         }
                        imageName = fileName;
                    }
                    catch (Exception ex)
                    {
                        error = ex.Message;
                    }
                    context.Response.Write("{imageName:'" + imageName + "', error:'" + error + "'}");
                }
            }
        }

        private string GetID()
        {
            return DateTime.Now.ToString("yyyyMMddHHmmssff");
        }

        private string GetExt(string fileName)
        {
            return fileName.Substring(fileName.IndexOf(".") + 1).ToLower();
        }

        private void DrawSmallImage(HttpPostedFile oldImg, int width, int height, string savePath)
        {
            Image image = Image.FromStream(oldImg.InputStream);

            bool isChange = false;

            if (width > 0 && height == 0)
            {
                isChange = image.Width > width;
            }
            if (width == 0 && height > 0)
            {
                isChange = image.Height > height;
            }
            if (width > 0 && height > 0)
            {
                isChange = (image.Width >= width && image.Height >= height);
            }

            if (isChange)
            {

                int newWidth = GetWidth(image, height, width);
                int newHeight = GetHeight(image, height, width);

                if (newWidth * height > width * newHeight)
                {
                    newHeight = height;
                }
                else
                {
                    newWidth = width;
                }

                Bitmap bitmap = new Bitmap(newWidth, newHeight);
                Graphics graphic = Graphics.FromImage(bitmap);
                //graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                //graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                graphic.DrawImage(image, 0, 0, newWidth, newHeight);

                //对大图加水印
                //Web.ocnfig中配置的产品大图片宽和高
                int productConfigBigImageWidth = ConvertTool.ToInt(System.Web.Configuration.WebConfigurationManager.AppSettings["ProductBW"]);
                int productConfigBigImageHeight = ConvertTool.ToInt(System.Web.Configuration.WebConfigurationManager.AppSettings["ProductBH"]);

                if (productConfigBigImageWidth == width && productConfigBigImageHeight == height)
                {
                    // 文字水印 开始

                    string waterMarkString = System.Web.Configuration.WebConfigurationManager.AppSettings["WaterMarkString"].ToString();

                    if (!string.IsNullOrEmpty(waterMarkString))
                    {

                        float waterMarkFontSize = float.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["WaterMarkFontSize"]);
                        string waterMarkFontFamily = System.Web.Configuration.WebConfigurationManager.AppSettings["WaterMarkFontFamily"].ToString();
                        string waterMarkFontColor = System.Web.Configuration.WebConfigurationManager.AppSettings["WaterMarkFontColor"].ToString();
                        float waterMarkPostionX = float.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["WaterMarkPostionX"]);
                        float waterMarkPostionY = float.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["WaterMarkPostionY"]);

                        System.Drawing.Graphics G = System.Drawing.Graphics.FromImage(bitmap);
                        System.Drawing.Font f = new Font(waterMarkFontFamily, waterMarkFontSize);
                        System.Drawing.Brush b = new SolidBrush(Color.FromName(waterMarkFontColor));
                        G.DrawString(waterMarkString, f, b, waterMarkPostionX, waterMarkPostionY);
                        G.Dispose();

                    }

                    // 文字水印 结束

                    // 图片水印 开始
                    string uploadFileFolder = System.Web.Configuration.WebConfigurationManager.AppSettings["UploadFileFolder"].ToString();
                    string waterMarkImage = System.Web.Configuration.WebConfigurationManager.AppSettings["WaterMarkImage"].ToString();

                    if (!string.IsNullOrEmpty(waterMarkImage))
                    {
                        float waterMarkPostionX = float.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["WaterMarkPostionX"]);
                        float waterMarkPostionY = float.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["WaterMarkPostionY"]);

                        System.Drawing.Image copyImage = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(uploadFileFolder + waterMarkImage));
                        Graphics a = Graphics.FromImage(bitmap);
                        a.DrawImage(copyImage, waterMarkPostionX, waterMarkPostionY, copyImage.Width, copyImage.Height);

                        copyImage.Dispose();
                        a.Dispose();
                        copyImage.Dispose();
                    }

                    //图片水印 结束
                }

                bitmap.Save(savePath, ImageFormat.Jpeg);
                graphic.Dispose();
                bitmap.Dispose();
            }
            else
            {
                oldImg.SaveAs(savePath);
            }
        }

        private int GetHeight(Image oldImg, int height, int width)
        {
            int newHeight = oldImg.Height * width / oldImg.Width;
            return newHeight > 0 ? newHeight : height;
        }

        private int GetWidth(Image oldImg, int height, int width)
        {
            int newWidth = oldImg.Width * height / oldImg.Height;
            return newWidth > 0 ? newWidth : width;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 

5.修改 ckeditor_3.1\ckeditor\plugins\image\dialogs 下的image.js文件(用_source目录下的源文件替换)下面只贴出关键部分。修改从image.js 424行的 onLoad(function(){  开始

onLoad: function() {
                if (dialogType != 'image')
                    this.hidePage('Link'); 	//Hide Link tab.
                var doc = this._.element.getDocument();
                this.addFocusable(doc.getById('btnResetSize'), 5);
                this.addFocusable(doc.getById('btnLockSizes'), 5);
                this.commitContent = commitContent;
                var imgDialogs = this;
                if (jQuery) {
                    if (window.AjaxUpload) {
                        var _btn = new AjaxUpload($($('.cke_dialog .cke_dialog_contents .cke_dialog_ui_button').get(0)), {
                            action: CKEDITOR.uploadImageHandleSrc,
                            name: 'myfile',
                            onSubmit: function(file, ext) {
                                if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
                                    alert('请选择图片上传!');
                                    return false;
                                }
                                this.disable();
                            },
                            onComplete: function(file, response) {
                                var data = eval('(' + response.replace(/<\/?\w+>/g, '') + ')');
                                this.enable();
                                if (data.imageName != null && data.imageName != '') {
                                    var newImageUrl = CKEDITOR.uploadImageFolder + data.imageName;
                                    imgDialogs.setValueOf('info', 'txtUrl', newImageUrl);
                                }
                                if (data.error != null && data.error != '') {
                                    alert(data.error);
                                }
                            }
                        });
                    }
                }
            }
6.给ckeditor目录下的config.js文件加上

CKEDITOR.uploadImageHandleSrc = '/QJAdmin/UpImage.ashx?imageFolder=image';
CKEDITOR.uploadImageFolder = '/UploadFile/image/';

CKEDITOR.uploadImageHandleSrc 为接受图片的服务,

CKEDITOR.uploadImageFolder 为图片的保存目录。

posted @ 2010-01-22 21:38  tySwing  阅读(1878)  评论(2)    收藏  举报