主题: 自己所写asp.net下的图片上传程序(.ashx版)!
作者: OA系统架构师, 发布日期: 2009-12-15 13:09:14, 浏览数: 12040

/**
  #为什么没有上传附件的地方啊?有的话告诉我? 可以把DEMO程序直接上传
*/
//--------------------下面是代码,只要创建Generic Handler(.ashx)以后 把这些代码粘贴就可以用--------
using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.IO;
using System.Text;

/**
 * 功能:KindEditor的Image Plugins服务器端代码(C#,.Net3.5)
 *
 * 使用:image.html里面的 <form name="uploadForm" method="post" enctype="multipart/form-data" action="{写该服务的地址}">
 *
 * 作者:HWG(XXJ) QQ:250233984
 *
 * 日期:2009年12月15日
 *
 * 版本:1.0测试版
 *
 * 声明:使用该代码的时请带版权信息!
 *
 */
namespace KindEditor.Service
{
    static class HttpPostedFileExtensions
    {
        /// <summary>
        /// 要上传的图片的相对路径 *必须从根(/)开始写 *项目中请先创建该目录
        /// </summary>
        public const string IMAGE_UPLOAD_PATH = "/ImageStore";

        /// <summary>
        /// 支持的图片类型
        /// </summary>
        private static string[] IMAGE_TYPE = new string[] { ".gif", ".jpg", ".jpeg", ".png", ".bmp" };

        /// <summary>
        /// 支持的图片的最大容量
        /// </summary>
        private static int IMAGE_MAX_LENGHT = 1 * 1024 * 1024; //1MB

        /// <summary>
        /// 服务器端图片名字前缀
        /// </summary>
        private const string IMAGE_START_NAME = "IS";

        /// <summary>
        /// 检查客户端传过来的文件是不是合法的图片
        /// </summary>
        /// <param name="file"></param>
        /// <param name="resultMessage"></param>
        /// <returns></returns>
        public static bool CheckImageFile(this HttpPostedFile file, out string resultMessage)
        {
            //Check Content Type
            string imageType = file.ContentType;
            if (imageType == null || !imageType.Trim().StartsWith("image"))
            {
                resultMessage = "不是图片类型,请选择正确的图片!";
                return false;
            }

            //Check Image File Extension
            string fileExtension = System.IO.Path.GetExtension(file.FileName);
            if (string.IsNullOrEmpty(fileExtension) || !IMAGE_TYPE.Contains<string>(fileExtension.Trim().ToLower()))
            {
                resultMessage = "不是图片类型,请选择正确的图片!";
                return false;
            }

            //Check Image File Lenght
            if (file.InputStream == null || file.InputStream.Length > IMAGE_MAX_LENGHT)
            {
                resultMessage = "图片大小不合法,请选择正确的图片!";
                return false;
            }
            resultMessage = string.Empty;
            return true;
        }

        /// <summary>
        /// 获取保存图片的路径和图片的新名字
        /// </summary>
        /// <param name="file"></param>
        /// <param name="currentContext"></param>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        /// <param name="resultMessage"></param>
        /// <returns></returns>
        public static bool GetPathAndName(this HttpPostedFile file, HttpContext currentContext, out string filePath, out string fileName, out string resultMessage)
        {
            resultMessage = string.Empty;
            fileName = string.Empty;
            filePath = currentContext.Server.MapPath(IMAGE_UPLOAD_PATH);
            if (string.IsNullOrEmpty(filePath) || !Directory.Exists(filePath))
            {
                resultMessage = "项目中不存在该虚拟路径,请重新配置!";

                return false;
            }
            string fileExtension = System.IO.Path.GetExtension(file.FileName);
            //格式: 图片名前缀_Year-Month-Day_Hour-Minute-Second_RandomNum.FileExtension
            do
            {
                fileName = string.Format("{0}_{1}_{2}{3}", IMAGE_START_NAME, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"), _getRandomNum(), fileExtension);
            }
            while (File.Exists(System.IO.Path.Combine(filePath, fileName)));
            return true;
        }

        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <returns></returns>
        public static string _getRandomNum()
        {
            Random seed = new Random();
            Random randomNum = new Random(seed.Next());
            return randomNum.Next().ToString();
        }
    }

    public class ImageInfo
    {
        public string Id { get; set; }
        public string Type { get; set; }
        public string Url { get; set; }
        public string ImgTitle { get; set; }
        public string ImgHeight { get; set; }
        public string ImgBorder { get; set; }
        public string ImgWidth { get; set; }
    }

    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Upload : IHttpHandler
    {
        private static string _cacheAlertString = string.Empty;

        private static string _cacheCallbackHtml = string.Empty;

        private static string _chcheHostUrl = string.Empty;

        public void ProcessRequest(HttpContext context)
        {
            HttpPostedFile file = context.Request.Files["imgFile"];
            if (file == null)
            {
                context.Response.Write(_getAlertStr("请选择图片!"));
                return;
            }
            string resultMessage;
            if (!file.CheckImageFile(out resultMessage))
            {
                context.Response.Write(_getAlertStr(resultMessage));
                return;
            }
            string fileName;
            string filePath;
            if (!file.GetPathAndName(context, out filePath, out fileName, out resultMessage))
            {
                context.Response.Write(_getAlertStr(resultMessage));
                return;
            }
            try
            {
                file.SaveAs(System.IO.Path.Combine(filePath, fileName));
            }
            catch (Exception ex)
            {
                //Log...
                context.Response.Write(_getAlertStr("图片上传失败,请重试或跟管理员联系!"));
                return;
            }
            //--------------------Do callback--------------------
            ImageInfo info = new ImageInfo();
            info.Id = context.Request.Form.Get("id");
            info.ImgBorder = context.Request.Form.Get("imgBorder");
            info.ImgHeight = context.Request.Form.Get("imgHeight");
            info.ImgTitle = context.Request.Form.Get("imgTitle");
            info.ImgWidth = context.Request.Form.Get("imgWidth");

            /* 带HostUrl的方式
            if(string.IsNullOrEmpty(_chcheHostUrl))
            {
                lock(_chcheHostUrl)
                {
                    if(string.IsNullOrEmpty(_chcheHostUrl))
                    {
                        string currentPath = context.Request.RawUrl.ToString();
                        string currentUrl = context.Request.Url.ToString();
                        string hostPath = currentUrl.Substring(0, currentUrl.LastIndexOf(currentPath));
                        _chcheHostUrl = hostPath;
                    }
                }
            }
            info.Url = string.Format("{0}{1}/{2}", _chcheHostUrl, HttpPostedFileExtensions.IMAGE_UPLOAD_PATH, fileName);
            */

            //不带HostUrl
            info.Url = string.Format("{0}/{1}", HttpPostedFileExtensions.IMAGE_UPLOAD_PATH, fileName);
            context.Response.Write(_getCallbackHtml(info));
        }

        /// <summary>
        /// 生成客户端提示信息
        /// </summary>
        /// <param name="meg"></param>
        /// <returns></returns>
        private static string _getAlertStr(string meg)
        {
            if (string.IsNullOrEmpty(_cacheAlertString))
            {
                lock (_cacheAlertString)
                {
                    if (string.IsNullOrEmpty(_cacheAlertString))
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append("<html>");
                        sb.Append("<head>");
                        sb.Append("<title>error</title>");
                        sb.Append("<meta http-equiv='content-type' content='text/html; charset=utf-8'>");
                        sb.Append("</head>");
                        sb.Append("<body>");
                        sb.Append("<html>");
                        sb.Append("<script type='text/javascript'>alert('@MSG@');history.back();</script>");
                        sb.Append("</body>");
                        sb.Append("</html>");
                        _cacheAlertString = sb.ToString();
                    }
                }
            }
            return _cacheAlertString.Replace("@MSG@", meg);
        }

        /// <summary>
        /// 获取回调的HTML
        /// </summary>
        /// <returns></returns>
        private static string _getCallbackHtml(ImageInfo imageInfo)
        {
            if (string.IsNullOrEmpty(_cacheCallbackHtml))
            {
                lock (_cacheCallbackHtml)
                {
                    if (string.IsNullOrEmpty(_cacheCallbackHtml))
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append("<html>");
                        sb.Append("<head>");
                        sb.Append("<title>Insert Image</title>");
                        sb.Append("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">");
                        sb.Append("</head>");
                        sb.Append("<body>");
                        sb.Append("@SCRIPT@");
                        sb.Append("</body>");
                        sb.Append("</html>");
                        _cacheCallbackHtml = sb.ToString();
                    }
                }
            }
            string script = "<script type=\"text/javascript\">parent.KE.plugin[\"image\"].insert('" + imageInfo.Id + "', '" + imageInfo.Url + "','" + imageInfo.ImgTitle + "','" + imageInfo.ImgWidth + "','" + imageInfo.ImgHeight + "','" + imageInfo.ImgBorder + "');</script>";
            return _cacheCallbackHtml.Replace("@SCRIPT@", script);
        }

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

作者: 明月穿潭, 发布日期: 2009-12-23 19:55:18

非常好用,谢谢,编译的时候要把命名空间去掉,方可编译成功

回复
作者: 明月穿潭, 发布日期: 2009-12-24 11:11:51
再次感谢
回复
作者: cong_er, 发布日期: 2009-12-24 16:10:30

楼主你好,我想问一下,图片上传的功能在asp。net mvc 中如何实现,谢谢!!!!

回复
作者: hmg43, 发布日期: 2010-07-09 00:25:17

看不太懂。请教提交页面上传图片成功后怎么在编辑器插入代码啊?

后台怎么调用js,不太明白。

回复
发表新帖 发表回复