using System;
using System.IO;
using System.Web;

namespace News.Web.kindeditor.php
{
    /// <summary>
    /// 
    /// </summary>
    public partial class upload : System.Web.UI.Page
    {
        string ext_arr = ".gif|.jpg|.jpeg|.png|.bmp"; //允许的格式
        int img_MaxSize = 1024 * 1024 * 2;//最大 2MB
        /// <summary>
        /// 
        /// </summary>
        protected void Page_Load(object sender, EventArgs e)
        {
            string sPath = Server.MapPath("../../upfile");
            HttpPostedFile pf = Request.Files[0];
            string file_url = "../../upfile/" + FileUpImg(sPath, pf, "ver");
            if (file_url.Length < 10)
            {
                alert("上传失败！");
                return;
            }
            ////插入图片，关闭层
            Response.Write("<html>");
            Response.Write("<head>");
            Response.Write("<title>Insert Image</title>");
            Response.Write("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">");
            Response.Write("</head>");
            Response.Write("<body>");
            Response.Write("<script type=\"text/javascript\">parent.KE.plugin['image'].insert('" + Request["id"] + "', '" + file_url + "','" + Request["imgTitle"] + "'," + Request["imgWidth"] + "," + Request["imgHeight"] + "," + Request["imgBorder"] + ");</script>");
            Response.Write("</body>");
            Response.Write("</html>");
        }
        ////提示，关闭层
        private void alert(string msg)
        {
            Response.Write("<html>");
            Response.Write("<head>");
            Response.Write("<title>error</title>");
            Response.Write("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">");
            Response.Write("</head>");
            Response.Write("<body>");
            Response.Write("<script type=\"text/javascript\">alert(" + msg + ");history.back();</script>");
            Response.Write("</body>");
            Response.Write("</html>");
        }

        /// <summary>
        /// 上传 图片(File html控件)
        /// </summary>
        /// <param name="sPath">保存的绝对路径（不含图片地址：如：D:/CC/BB）</param>
        /// <param name="imgFile">HttpPostedFile</param>
        /// <param name="ver">图片前缀 如: v_</param>
        /// <returns>新的文件名</returns>
        private string FileUpImg(string sPath, HttpPostedFile imgFile, string ver)
        {
            string newfilename = "";

            if (imgFile != null)
            {
                string fileExt = System.IO.Path.GetExtension(imgFile.FileName);
                if (ext_arr.IndexOf(fileExt.ToLower()) >= 0)
                {
                    if (imgFile.ContentLength > img_MaxSize)
                    {
                        HttpContext.Current.Response.Write("<script>alert('图片大小不能够超过：" + img_MaxSize / (1024 * 1024) + "M!');</script>");
                        return null;
                    }
                    try
                    {
                        newfilename = ver + GetNewFileName(imgFile.FileName).ToLower();

                        if (File.Exists(sPath + "/" + newfilename) == false)
                        {
                            Directory.CreateDirectory(sPath);
                            imgFile.SaveAs(sPath + "/" + newfilename);
                        }
                        else
                        {
                            HttpContext.Current.Response.Write("<script>alert('该文件已经存在!');</script>");
                            return null;
                        }

                    }
                    catch (Exception ex)
                    {
                        HttpContext.Current.Response.Write("<script>alert('错误：" + ex.Message.ToString() + "');</script>");
                        return null;
                    }
                }
                else
                {
                    HttpContext.Current.Response.Write("<script>alert('只能上传图片!允许的格式：" + ext_arr + "');</script>");
                    return null;
                }

            }
            else
            {
                HttpContext.Current.Response.Write("<script>alert('请选择图片!');</script>");
                return null;
            }
            return newfilename;
        }
        /// <summary>
        /// 根据原文件名 生成 随机文件名
        /// </summary>
        /// <param name="FileName">原文件名</param>
        /// <returns>新的文件名</returns>
        private string GetNewFileName(string FileName)
        {//跟据文伯名产生一个由时间+随机数组成的一个新的文件名 
            string newfilename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString()
            + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString()
            + DateTime.Now.Second.ToString() + DateTime.Now.Minute.ToString()
            + DateTime.Now.Millisecond.ToString()
                //+ rand.Next(1000).ToString() 
            + FileName.Substring(FileName.LastIndexOf("."), FileName.Length - FileName.LastIndexOf("."));
            return newfilename;
        }
    }
}
