网页前端设计

http://www.86y.org

搜索文章

kindeditor 批量上传加水印附源文件下载.net版本

用声音读出全文关注我吧
 2016/12/22 17:31:45 阅读次数:8142

一、概述:

本次修改的是最新版本kindeditor-4.1.10 主要是针对.net版,批量上传添加水印,水印可以选择文字或是图片。修改过程挺奇葩,因为有些API不熟,导至走了不少弯路,言而总之还是惊喜。喜欢本实例的朋友可以下载DEMO源文件,文章底部附下载地址。效果图如下:

kindeditor 批量上传加水印附源文件下载.net版本

 

二、环境要求:

1、.net4.0 版本或以上

2、添加引用 LitJson.dll,下载地址:http://download.csdn.net/detail/pukuimin1226/5851711

只要以上两个条件就可以在IIS下运行了。

 

三、修改代码:

1、kindeditor-all.js,本人没有使用精简js,因为方便修改。

搜索uploadDesc: uploadDesc,在后面添加如下代码

"<div style='position:absolute;right:82px;top:0;color:#999'>选择图片水印类型<select style='margin-left:10px' id='watertype'><option value=''>请选择水印类型</option><option value='image'>图片水印</option><option value='txt'>文字水印</option></select></div>"

修改后:

uploadDesc: uploadDesc + "<div style='position:absolute;right:82px;top:0;color:#999'>选择图片水印类型<select style='margin-left:10px' id='watertype'><option value=''>请选择水印类型</option><option value='image'>图片水印</option><option value='txt'>文字水印</option></select></div>"

到这一步已经可以预览到效果了。水印选择可以显示出来了,但是还没有传参数到接口如(/kindeditor-4.1.10/asp.net/upload_json.ashx?dir=image)

接下来要添加water=image参数到这个接口

 

2、找到K('.ke-swfupload-startupload input', self.div).click(function () 这个事件,这个是点击 【开始上传】事件

在这个方法上面先定义一个变量

var defaultuploadurl = ""; //保存最早的上传url,防止water参数重复累加

整个事件代码替换成

´
K('.ke-swfupload-startupload input', self.div).click(function () {
    //新增水印功能 开始
    var wt = document.getElementById('watertype').options[document.getElementById('watertype').selectedIndex].value;//获取水印选择的值
    var ds = self.swfu.settings.upload_url;//上传url
    var newuploadurl = "";
    if (ds.indexOf("water") == -1)//判断上传url有没有water参数,没有就把值保存在 defaultuploadurl中。
    {
        defaultuploadurl = self.swfu.settings.upload_url;
    }
    newuploadurl = defaultuploadurl + "&water=" + wt;
    self.swfu.setUploadURL(newuploadurl);
    var dd = self.swfu;
    //新增水印功能 结束

    self.swfu.startUpload();
});

到这一步已经可以看到传到接口(/kindeditor-4.1.10/asp.net/upload_json.ashx?dir=image&water=image)

前端到这里已经完成。

 

3、后台水印处理:(上传过程不在详述)

<%@ webhandler Language="C#" class="Upload" %>

/**
 * KindEditor ASP.NET
 *
 * 本ASP.NET程序是演示程序,建议不要直接在实际项目中使用。
 * 如果您确定直接使用本程序,使用之前请仔细确认相关安全设置。
 *
 */

using System;
using System.Collections;
using System.Web;
using System.IO;
using System.Globalization;
using LitJson;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;  

public class Upload : IHttpHandler
{
	private HttpContext context;

	public void ProcessRequest(HttpContext context)
	{
		String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1);
		
		//文件保存目录路径
        String savePath = "/upload/image/";

		//文件保存目录URL
        String saveUrl = "/upload/image/";

        //水印logo
        string waterlogo = "/App_Code/logo.png";

		//定义允许上传的文件扩展名
		Hashtable extTable = new Hashtable();
		extTable.Add("image", "gif,jpg,jpeg,png,bmp");
		extTable.Add("flash", "swf,flv");
		extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
		extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

		//最大文件大小
		int maxSize = 1000000; //1M
		this.context = context;

		HttpPostedFile imgFile = context.Request.Files["imgFile"];
		if (imgFile == null)
		{
			showError("请选择文件。");
		}

        String dirPath = context.Server.MapPath(savePath);
        if (!Directory.Exists(dirPath))
        {
            Directory.CreateDirectory(dirPath);
        }

        String dirName = context.Request.QueryString["dir"] != null ? context.Request.QueryString["dir"] : "image";
        String fileName = imgFile.FileName;
        String fileExt = Path.GetExtension(fileName).ToLower();

        if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
        {
            showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。");
        }
        if (dirName == "image")
        {
            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                showError("上传文件大小超过限制。");
            }
            if (!isPic(imgFile))
            {
                showError("上传文件不合法!");
            }
        }





        //创建文件夹
        //dirPath += dirName + "/";
        //saveUrl += dirName + "/";
        if (!Directory.Exists(dirPath))
        {
            Directory.CreateDirectory(dirPath);
        }
        String ymd = DateTime.Now.ToString("yyyyMM", DateTimeFormatInfo.InvariantInfo);
        dirPath += ymd + "/";
        saveUrl += ymd + "/";
        if (!Directory.Exists(dirPath))
        {
            Directory.CreateDirectory(dirPath);
        }

        //edit_upload_fileName
        //string sessionUploadFileName = string.Empty;
        //if (HttpContext.Current.Session["edit_upload_fileName"] != null)
        //{
        //    sessionUploadFileName = HttpContext.Current.Session["edit_upload_fileName"].ToString();
        //}
        //String newFileName = sessionUploadFileName + DateTime.Now.ToString("yyyyMMddHHmmssffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
        //String filePath = dirPath + newFileName;
        //imgFile.SaveAs(filePath);
        //String fileUrl = saveUrl + newFileName;

        //水印start        
        String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo);
        String filePath = dirPath + newFileName + fileExt;
        imgFile.SaveAs(filePath);
        String fileUrl = saveUrl + newFileName + fileExt;
        Image image = System.Drawing.Image.FromFile(filePath);
        string newPath = "";
        if (context.Request["water"] != null && context.Request["water"].ToString() != "")
        {
            Graphics g = Graphics.FromImage(image);
            if (context.Request["water"].ToString() == "txt")
            {
                //添加文字水印                
                g.DrawImage(image, 0, 0, image.Width, image.Height);
                Font f = new Font("Arial", 14);
                Brush b = new SolidBrush(Color.YellowGreen);
                string addText = "www.soft0754.com";
                g.DrawString(addText, f, b, image.Width - 200, image.Height - 40);                
            }
            //图片水印
            //判断图片大于200*200才加水印
            else if (context.Request["water"].ToString() == "image")
            {
                if (image.Width > 200 && image.Height > 200)
                {
                    System.Drawing.Image copyImage = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("/") + waterlogo);
                    g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width - 10, image.Height - copyImage.Height - 10, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);                  
                }                
            }

            g.Dispose();
            newPath = dirPath + newFileName + "_new" + fileExt;
            image.Save(newPath);
            image.Dispose();
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            newPath = saveUrl + newFileName + "_new" + fileExt;
            //fileUrl = newPath;
        }
        else {
            newPath = fileUrl;
        }
            
            
        //保存加水印过后的图片,删除原始图片        
        //newPath = dirPath + newFileName + "_new" + fileExt;
        
        //水印end


        Hashtable hash = new Hashtable();
        hash["error"] = 0;
        hash["url"] = newPath;
        hash["test"] = saveUrl + newFileName + "_new" + fileExt;
        
        context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
        context.Response.Write(JsonMapper.ToJson(hash));
        context.Response.End();
	}

	private void showError(string message)
	{
		Hashtable hash = new Hashtable();
		hash["error"] = 1;
		hash["message"] = message;
		context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
		context.Response.Write(JsonMapper.ToJson(hash));
		context.Response.End();
	}

	public bool IsReusable
	{
		get
		{
			return true;
		}
	}

    public bool isPic(HttpPostedFile imgFile)
    {
        int fileLen = imgFile.ContentLength;
        byte[] imgArray = new byte[fileLen];
        imgFile.InputStream.Read(imgArray, 0, fileLen);
        MemoryStream ms = new MemoryStream(imgArray);
        BinaryReader br = new BinaryReader(ms);
        string fileclass = "";
        byte buffer;
        try
        {
            buffer = br.ReadByte();
            fileclass = buffer.ToString();
            buffer = br.ReadByte();
            fileclass += buffer.ToString();
        }
        catch
        { }
        br.Close();
        ms.Close();
        //
        try
        {
            //读取上传的文件是否是图片对象,异常则删除图片
            System.Drawing.Image uploadedImg = System.Drawing.Image.FromStream(imgFile.InputStream);
            if (uploadedImg.Width < 1 || uploadedImg.Height < 1)
            {
                return false;
            }
            uploadedImg.Dispose();
        }
        catch
        {
            return false;
        }
        //
        FileExtension[] fileEx = { FileExtension.GIF, FileExtension.BMP, FileExtension.JPG, FileExtension.PNG };
        foreach (FileExtension fe in fileEx)
        {
            try
            {
                if (Int32.Parse(fileclass) == (int)fe)
                {
                    if (truePic(System.Text.Encoding.ASCII.GetString(imgArray)))
                    {
                        return true;
                    }
                    return false;
                }
            }
            catch
            { }

        }
        return false;
    }

    //判断上传文件中是否包含关键字
    public bool truePic(string str)
    {
        string sStr = ".getfolder|.createfolder|.deletefolder|.createdirectory|.deletedirectory|.saveas|wscript.shell|script.encode|server.|.createobject|execute|activexobject|language=|exec |insert |select |delete |update |truncate |declare |iframe |Response|Request(| Eval|Eval |Eval(|%Eval|script |using";
        string[] ck = sStr.Split('|');
        string strsql = str;
        for (int i = 0; i < ck.Length; i++)
        {
            if (str.IndexOf(ck[i]) != -1 || str.ToUpper().IndexOf(ck[i].ToUpper()) != -1)
            {
                return false;
            }
        }
        return true;
    }

    //文件类型
    public enum FileExtension
    {
        JPG = 255216,
        GIF = 7173,
        PNG = 13780,
        BMP = 6677,
        SWF = 6787,
        SWF2 = 7087,
        RAR = 8297,
        ZIP = 8075,
        DOC = 208207,
        DOCX = 8075,
        XLS = 208207,
        XLS2 = 198243,
        XLSX = 8075,
        //_7Z = 55122,
        // 255216 jpg;   
        // 7173 gif;   
        // 6677 bmp,   
        // 13780 png;   
        // 6787 swf   
        // 7790 exe dll,   
        // 8297 rar   
        // 8075 zip   
        // 55122 7z   
        // 6063 xml   
        // 6033 html   
        // 239187 aspx   
        // 117115 cs   
        // 119105 js   
        // 102100 txt   
        // 255254 sql  
        /*
        DOC = 208207,
        DOCX = 8075,
        XLS = 208207,
        XLSX = 8075,
        JS = 239187,
        TXT = 7067,
        MP3 = 7368,
        WMA = 4838,
        MID = 7784,
        */
    }
}

到这里你就可以试试效果了。

百度网盘下载地址:链接: http://pan.baidu.com/s/1bTtO3k 密码: sb7d

 

四、结语:

大家试用后有什么问题可以与我交流。


大家有什么问题或技术上的想法可以在此与大家分享,也可以加入前端爱好者QQ群(141999928)一起学习进步:【幸凡前端技术交流群】
如需转载请注明出处:http://www.86y.org/art_detail.aspx?id=815【kindeditor 批量上传加水印附源文件下载.net版本】幸凡学习网
0

如果您觉得本文的内容对您的学习有所帮助,捐赠与共勉,支付宝(左)或微信(右)

阅读全文内容关闭