<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Upload.aspx.cs" Inherits="Kesion.NET.WebSite.Admin.Include.UploadUI" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="Kesion.Cache" %>
<%@ Import Namespace="Kesion.Publics" %>
<%@ Import Namespace="Kesion.BLL" %>
<%@ Import Namespace="Kesion.Config" %>
<%@ Import Namespace="Kesion.Components" %>
<%@ Import Namespace="Kesion.XML" %>
<!DOCTYPE html>
<html>
<head runat="server">
    <title>上传</title>
     <link href="../../admin/images/style.css" rel="stylesheet" type="text/css" />
     <script src="../../KS_Inc/Jquery.js" type="text/javascript"></script>
     <script src="../../KS_Inc/Kesion.Common.js" type="text/javascript"></script>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <meta http-equiv="pragma" content="no-cache" /> 
    <script type="text/javascript" src="/ks_inc/webuploader/js/webuploader.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/ks_inc/webuploader/css/webuploader.css">
   <link rel="stylesheet" type="text/css" href="/ks_inc/webuploader/css/style.css">

</head>
<body<%=(!string.IsNullOrEmpty(KSCMS.S("bgcolor"))&&KSCMS.S("bgcolor").Length<10) ? " style='background:#"+Utils.RemoveXss(KSCMS.S("bgcolor"))+"'" : string.Empty %>>
<script runat="server">
    int upBySwf = 1;  //启用swfupload上传 1 启用 0不启用
    ModelInfo __info = null;
    string fieldId = "-1";
    string UpType = KSCMS.S("UpType");
    string CurrPath = KSCMS.S("CurrPath");   //从selectfile.aspx 文件上传时用到
    int isPic = Utils.StrToInt(KSCMS.S("IsPic"),0); //自定义字段，是不是图片字段 1是 0不是
    int AddWaterMark = Utils.StrToInt(KSCMS.S("AddWaterMark"), 1);
    int CreateThumbs = Utils.StrToInt(KSCMS.S("CreateThumbs"), 1);
    int channelId = Utils.StrToInt(KSCMS.S("channelid"));
    string FieldXML = string.Empty;
    string module = string.Empty;
    XmlNode xn = null;
    string btnText = "选择上传...";
    int btnWidth = 110;
    int btnHeight = 25;
    string adminUserFaceID = string.Empty; //后台上传头像的用户ID
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["adminUserFaceID"] != null) adminUserFaceID = Session["adminUserFaceID"].ToString();

        if (Utils.StrToInt(KSCMS.S("bthwidth")) > 0)
        {
            btnWidth = Utils.StrToInt(KSCMS.S("bthwidth"));
        }
        if (Utils.StrToInt(KSCMS.S("btnheight")) > 0)
        {
            btnHeight = Utils.StrToInt(KSCMS.S("btnheight"));
        }
        if (!string.IsNullOrEmpty(KSCMS.S("text")))
        {
            btnText = KSCMS.S("text");
        }


        if (KSCMS.S("bgcolor").Length > 10)
        {
            KSCMS.Die("error!");
        }
        if (!string.IsNullOrEmpty(KSCMS.S("fieldid")))
        {
            fieldId = KSCMS.S("fieldid");
            if (fieldId.IndexOf("'")!=-1 || fieldId.IndexOf("<")!=-1 ||fieldId.IndexOf("(")!=-1)
            {
                KSCMS.Die("error!");
            }

        }
        if (fieldId.ToLower() == "defaultpic") isPic = 1;
        if (channelId>0 && channelId!=10001 && channelId!=10002)
        {
            __info = ModelManage.GetModelInfo(channelId);
            if (__info != null)
            {
                FieldXML = __info.FieldsXML;
                #region 模型配置是否默认生成缩略图及水印
                if (Utils.InArray("11", MyCache.GetCacheModel(Utils.StrToInt(channelId), 31), ","))
                {
                    CreateThumbs =1;
                }
                else
                {
                    CreateThumbs =0;
                }
                if (Utils.InArray("12", MyCache.GetCacheModel(Utils.StrToInt(channelId), 31), ","))
                {
                    AddWaterMark =1;
                }
                else
                {
                    AddWaterMark =0;
                }
                #endregion

            }
        }

        #region 读配置文件
        module = KSCMS.S("module");
        if (!string.IsNullOrEmpty(module))
        {
            #region 模块配置上传
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath("~/config/uploadsetting.config"));
            xn = doc.SelectSingleNode("//uploadsetting/item[@module='" + module + "']");
            if (xn == null)
            {
                KSCMS.Die("error!");
            }
            if (xn.Attributes["btntext"] != null)
            {
                btnText = xn.SelectSingleNode("@btntext").InnerText;
            }
            if (xn.Attributes["btnwidth"] != null)
            {
                btnWidth = Utils.StrToInt(xn.SelectSingleNode("@btnwidth").InnerText);
            }
            if (xn.Attributes["btnheight"] != null)
            {
                btnHeight = Utils.StrToInt(xn.SelectSingleNode("@btnheight").InnerText);
            }
            if (xn.Attributes["showthumb"]!= null)
            {
                isPic = Utils.StrToInt(xn.SelectSingleNode("@showthumb").InnerText);
            }
            if (xn.Attributes["addwatermark"] != null)
            {
                AddWaterMark = Utils.StrToInt(xn.SelectSingleNode("@addwatermark").InnerText);
            }
            if (xn.Attributes["createthumbs"] != null)
            {
                CreateThumbs = Utils.StrToInt(xn.SelectSingleNode("@createthumbs").InnerText);
            }

#endregion
        }

        #endregion



        #region 从selectfile.aspx文件来的上传，允许改变上传路径,所以要判断上传路径合法性
        if (!string.IsNullOrEmpty(CurrPath))
        {
            //正则表达式   
            string strExp = @"^" + string.Concat(KSCMS.GetInstallDir(), MyCache.GetCacheConfig(22), @"\/");
            //创建正则表达式对象   
            Regex myRegex = new Regex(strExp);
            if (!myRegex.IsMatch(CurrPath))
            {
                KSCMS.Die("非法上传目录!");
            }
        }
        #endregion

    }


</script>  
    
   
<%      
    if (upBySwf == 1)  //用webuploader
    { %>
      <script>
          <%
          if (!string.IsNullOrEmpty(module))  //XML配置上传
          {
        %>
          var limitSize=<%=xn.SelectSingleNode("@limitsize").InnerText%>; //限制大小 KB
          var fileExt="<%=Utils.getSwfUploadExt(xn.SelectSingleNode("@allowext").InnerText) %>"
          <%
          }
          else if (fieldId == "-1")
          {
              if (__info != null)
              {  //有指定模型
               %>
		 	    var limitSize=<%=__info.AllowUpFilesSize%>; //限制大小 KB
			    var fileExt="<%=Utils.getSwfUploadExt(string.Concat(__info.AllowUpFlashType, "|", __info.AllowUpMediaType, "|", __info.AllowUpOtherType, "|", __info.AllowUpPhotoType, "|", __info.AllowUpRealType)) %>" //限制扩展名
			     <%}
          else {    //未指定模型读取整站配置的%>
			     var limitSize=<%=MyCache.GetCacheConfig(51)%>; //限制大小 KB
			     var fileExt="<%=Utils.getSwfUploadExt(MyCache.GetCacheConfig(52)) %>"
              <%} %>
          <%}
          else if (fieldId.ToLower() == "doc")
          {
		 %>
          var limitSize=<%=__info.AllowUpFilesSize%>; //限制大小 KB
          var fileExt="*.doc;*.docx" //限制扩展名
          <%}
          else if (fieldId.ToLower() == "defaultpic")
          {
		 %>
		 	var limitSize=<%=__info.AllowUpFilesSize%>; //限制大小 KB
			var fileExt="<%=Utils.getSwfUploadExt(__info.AllowUpPhotoType) %>" //限制扩展名
          <%}
          else if (channelId == 10001)
          { //会员注册时的上传字段 
              string FieldsXML = string.Empty;
              using (DataTable dt = DataFactoryUser.GetDataTable("select top 1 * From KS_UserConfig"))
              {
                  if (dt.Rows.Count > 0)
                  {
                      DataRow dr = dt.Rows[0];
                      FieldsXML = dr["userfield"].ToString();
                  }
                  else
                  {
                      KSCMS.Die("找不到会员配置表，请检查!");
                  }
              }

              ArrayList field = new ArrayList();
              field = XmlObject.GetSubElementByAttributeFromStr(FieldsXML, "Field", "@Name", KSCMS.S("FieldID"));
       %>
          var limitSize=<%=field[8].ToString() %>;
          var fileExt="<%=Utils.getSwfUploadExt(field[7].ToString()) %>";
         <%}
          else if (channelId == -123)
          {
              #region 课程自定义上传字段
              using(DataTable dt=DataFactory.GetDataTable("select top 1 * From KS_CosField Where id=" + Utils.StrToInt(KSCMS.S("id"))))
              {
                  if (dt.Rows.Count > 0)
                  {
                      Response.Write("var limitSize=" + dt.Rows[0]["maxfilesize"].ToString() + ";\n");
                      Response.Write("var fileExt='" + Utils.getSwfUploadExt(dt.Rows[0]["AllowFileExt"].ToString()) + "';\n");
                  }
                  else
                  {
                      KSCMS.Die("error");
                  }
              }
              #endregion
          }
          else
          {
             %>
		 	var limitSize=<%=Utils.StrToInt(XmlObject.GetStrXmlNode(FieldXML, string.Format(@"//Model/Field[@Name='{0}']/MaxFileSize", fieldId)), 0)%>; //限制大小 KB
			var fileExt="<%=Utils.getSwfUploadExt(XmlObject.GetStrXmlNode(FieldXML, string.Format(@"//Model/Field[@Name='{0}']/AllowFileExt", fieldId))) %>" //限制扩展名
		<%}
          
           %>
      </script>


    	<table cellspacing="0" cellspadding="0" border="0">
		 <tr>
		  <td width="<%=btnWidth%>">
		    <div id="uploader" class="wu-example">
                <div class="btns">
                    <span id="picker" style="width:<%=btnWidth%>px;height:<%=btnHeight%>px;line-height:<%=btnHeight%>px;"><%=btnText%></span>
                </div>
            </div>
		 </td>
	<%
           if (!string.IsNullOrEmpty(module))
           {

               if (xn.Attributes["tips"] != null )
               {
                       string tips = xn.SelectSingleNode("@tips").InnerText;
                       if (!string.IsNullOrEmpty(tips))
                       {
                           string sizeStr = string.Empty;
                           float size = Utils.StrToFloat(xn.SelectSingleNode("@limitsize").InnerText);
                           if (size > 1024)
                           {
                               sizeStr = (size / 1024).ToString("F0") + "MB";
                           }
                           else
                           {
                               sizeStr = xn.SelectSingleNode("@limitsize").InnerText + "KB";
                           }
                           tips = Utils.ReplaceString(tips, "{#size}", sizeStr, true);
                           tips = Utils.ReplaceString(tips, "{#ext}", xn.SelectSingleNode("@allowext").InnerText, true);
                           Response.Write(string.Format(@"<td style='color:#999;padding-left:5px;'>{0}</td>", tips));
                       }
                  
               }
           }
     if (isPic==1)
      {%>
		  <td><label><input type="checkbox" name="DefaultUrl" id="DefaultUrl" value="1"<%=CreateThumbs==1?" checked":string.Empty %>>缩略图</label> 
            <%if (ConfigManage.GetConfig().WaterMarkStatus!=0){ %>     
             <label><input name="AddWaterFlag" type="checkbox" id="AddWaterFlag" value="1"<%=AddWaterMark==1?" checked":string.Empty %>>水印</label> 
              <%} %>
             <%
          string thumbWidth = string.Empty;
          string thumbHeight = string.Empty;
          if (channelId > 0)
          {
              thumbWidth = MyCache.GetModelSetting(channelId, 6);
              thumbHeight = MyCache.GetModelSetting(channelId, 7);
          }
          if (string.IsNullOrEmpty(thumbWidth))  thumbWidth = !string.IsNullOrEmpty(KSCMS.S("Width")) ? KSCMS.S("width") : ConfigManage.GetConfig().ThumbsWidth.ToString();
          if (string.IsNullOrEmpty(thumbHeight)) thumbHeight = !string.IsNullOrEmpty(KSCMS.S("height")) ? KSCMS.S("height") : ConfigManage.GetConfig().ThumbsHeight.ToString();

          %>
		  <strong>缩略图大小：</strong>宽<input name="PicWidth" id="PicWidth" class="textbox" style="width:40px;text-align:center" value="<%=thumbWidth %>">PX 高<input name="PicHeight" id="PicHeight" class="textbox" style="width:40px;text-align:center" value="<%=thumbHeight%>">PX
		  </td>
		  <%}%>
         
		 </tr>
         <tr>
         <td colspan="2"><div id="thelist" class="uploader-list"></div> <!--用来存放文件信息 显示进度等--></td>
         </tr>
		</table>


    <script>
        // 文件上传
        jQuery(function () {
            var $ = jQuery,
                $list = $('#thelist'),
                state = 'pending',
                uploader;
            uploader = WebUploader.create({
                compress: false,//不启用压缩
                // 不压缩image
                resize: false,
                // swf文件路径
                swf:'/ks_inc/webuploader/js/Uploader.swf',
                // 文件接收服务端。
                server: 'uploads.ashx',
               <%if (UpType == "UpPhoto") { //图片频道%>
                 formData: {
                     "AdminLoginCode":"<%=Kesion.Publics.KSCMS.GetCookie("Admin","AdminLoginCode") %>",
                     "adminuser":"<%=Kesion.Publics.KSCMS.GetCookie("Admin","AdminUser") %>",
                     "adminpass":"<%=Kesion.Publics.KSCMS.GetCookie("Admin","AdminPass") %>",
                     "PowerList":"<%=Kesion.BLL.KSSecurity.ReturnPowerList() %>",
                     "usertype":"<%=Kesion.Publics.KSCMS.GetCookie("Admin","UserType") %>",
                     "CreateThumbs":1,
                     "ChannelID":2,
                     "AutoRename":4,
                     "fieldid":"-1",
                     "upbyswf":1
                    } 
            <%}else {%>
                    formData: {
                        "adminUserFaceID":"<%=adminUserFaceID%>", 
                        "AdminLoginCode":"<%=KSCMS.GetCookie("Admin","AdminLoginCode") %>",
                        "adminuser":"<%=KSCMS.GetCookie("Admin","AdminUser") %>",
                        "adminpass":"<%=KSCMS.GetCookie("Admin","AdminPass") %>",
                        "PowerList":"<%=KSSecurity.ReturnPowerList() %>",
                        "usertype":"<%=KSCMS.GetCookie("Admin","UserType") %>",
                        "upBySwf":"1",
                        "UpType":"<%=UpType%>",
                        "module":"<%=module%>",
                        "ChannelID":<%=channelId%>,
                        "id": "<%=Utils.StrToInt(KSCMS.S("id"))%>",
                        "fid": "<%=Utils.StrToInt(KSCMS.S("id"))%>",
                        "FieldID":"<%=fieldId%>",
                        "ispic":<%=isPic%>,
                        "AutoRename":4,
                        "AddWaterMark":<%=AddWaterMark%>,
                        "CreateThumbs":<%=CreateThumbs%>
                        <%if (isPic==1){ %>,"ThumbsWidth":jQuery('#PicWidth').val(),"ThumbsHeight":jQuery('#PicHeight').val()  <%} %>
                    } 
                <%}%>
                ,
              <%if (isPic == 1) { %>
                accept: { // 只允许选择图片文件格式
                    title: 'Images',
                     extensions: 'gif,jpg,jpeg,bmp,png',
                     mimeTypes: 'image/!*'
                },
                <%}%>
                
                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                fileSingleSizeLimit: limitSize*1024, //限制单个上传图片的大小
                pick: '#picker'
            });

            uploader.on( 'uploadBeforeSend', function( block, data ) {
                 <%if (isPic == 1) { %>
                    // 修改data可以控制发送哪些携带数据。  
                    data.ThumbsWidth = jQuery('#PicWidth').val();
                    data.ThumbsHeight=jQuery('#PicHeight').val();
                    if ($("#DefaultUrl").prop('checked')){
                        data.CreateThumbs=1;
                    }
                    if ($("#AddWaterFlag").prop('checked')){
                        data.AddWaterMark=1;
                    }
                <%}else if (UpType == "UpPhoto") {%>
                if (jQuery("#AddWaterFlag",parent.document).prop('checked')){
                    data.AddWaterMark=1;
                }
                <%}%>
        });

        // 当有文件添加进来的时候
        uploader.on('fileQueued', function (file) {
           
            $list.html('<div id="' + file.id + '" class="item">' +
                '<h4 class="info" style="display:none">' + file.name + '</h4>' +
                '<p class="state"  style="display:none">等待上传...</p>' +
            '</div>');
            

            //触发上传
            if (state === 'uploading') {
                uploader.stop();
            } else {
                uploader.upload();
            }
        });

        // 文件上传过程中创建进度条实时显示。
        uploader.on('uploadProgress', function (file, percentage) {
            console.log(document.getElementById(file.id))
            
            $('#'+file.id).html('<div class="progress progress-striped active">' +
                      '<div class="progress-bar" role="progressbar" style="width: '+percentage * 100+'%">' +
                      '</div>' +
                    '</div>')
            
        });

        uploader.on('error', function (code) {
            var err = '';
            switch (code) {
                case 'F_EXCEED_SIZE':
                    err += '单个文件大小不得超过' +  uploader.options.fileSingleSizeLimit + 'kb！';
                    break;
                case 'Q_EXCEED_NUM_LIMIT':
                    err += '最多只能上传' +  uploader.options.fileNumLimit + '张！';
                    break;
                case 'Q_EXCEED_SIZE_LIMIT':
                    err += '上传总大小超出'+limitSize;
                    break;
                case 'Q_TYPE_DENIED':
                    err += '无效图片类型，请上传正确的图片格式！';
                    break;
                case 'F_DUPLICATE':
                    err+='不能重复上传相同文件！' ;
                    break;
                default:
                    err += '上传错误，请刷新重试！错误代码：'+code;
                    break;
            }
            alert(err);
            return false;
        });



        uploader.on('uploadSuccess', function (file,response) {
            if (response.status==0){
                alert(response.error);
                return;
            }
            var serverData=response.url;
            
           // console.log(response);
            <%if (UpType == "UpByBar")
        {  //显示进度等%>
               <%if (fieldId=="-1"){
					       if (KSCMS.S("from")=="selectfile"){
					       %>
                            jQuery("#FileUrl",parent.document).val(serverData);
                            $(window.parent.document).find("#FolderList").attr("src","FileList.aspx?ChannelID=<%=channelId %>&CurrPath=<%=CurrPath %>"); 
                            $(window.parent.document).find("#PreviewArea").attr("src","Preview.aspx?FilePath="+serverData); 
					       <%}else{ %>
					        parent.SetDownUrlByUpLoad(serverData,file.size);  //下载的软件

					     <%}
					     }else{ %>
						  parent.document.getElementById('<%=fieldId%>').value=serverData;
						<%} %>
            <%}else if (UpType == "UpPhoto")  //图片频道
        {
           %>var src=serverData.split('@');
            parent.addImage(src[0],src[1],unescape(src[2]));
<%
        }
        else
        {

            if (!string.IsNullOrEmpty(module))  //XML配置上传
            {
                string dofun = xn.InnerText;
                dofun = Utils.ReplaceString(dofun, "{#return}", "serverData", true);
                dofun = Utils.ReplaceString(dofun, "{#fieldid}", fieldId, true);
                Response.Write(dofun);

            }
            else if (fieldId.ToLower() == "doc")
            {
            %>
				    parent.document.getElementById('<%=fieldId%>').value=serverData;
				    parent.document.getElementById('<%=fieldId%>').focus();
				    parent.document.getElementById('ipdoc').innerHTML = "<div style=\"border:solid 1px #FF0000\">使用动态创建的$(document).ready(function)方法</div>";
			  <%}
            else if (fieldId.ToLower() != "defaultpic")
            { //自定义字段 %>
			            parent.document.getElementById('<%=fieldId%>').value=serverData;
			            alert('恭喜文件上传成功！');
					     //KesionJS.AlertByTime('1','恭喜文件上传成功！',2);
			      <%}
            else
            {%>
				    
				         if (serverData.indexOf('@')==-1){
				           parent.document.getElementById('<%=fieldId%>').value=serverData;
				         }else{
				            var d=serverData.split('@');
				            parent.document.getElementById('DefaultPic').value=d[1];
				             try{
				                 parent.document.getElementById('BigPhoto').value=d[0];
				             
                             }catch(e){
				             }
				             <%if (__info.BasicType == 1)
            {%>
				                 parent.insertHTMLToEditor('<img src="'+d[0]+'" />');
				            <%}%>
				         }
				        $('#show<%=fieldId%>', parent.document).attr("src",d[1]);
			     <%}
            } %>

           // $('#' + file.id).find('p.state').text('已上传').show().removeClass("state");

                
            });

            uploader.on('uploadError', function (file) {
                $('#' + file.id).find('p.state').text('上传出错');
            });

            uploader.on('uploadComplete', function (file) {
                $('#' + file.id).find('.progress').fadeOut();
                $('#' + file.id).find('p.state').text('已上传').show().removeClass("state");

            });

            uploader.on('all', function (type) {
                if (type === 'startUpload') {
                    state = 'uploading';
                } else if (type === 'stopUpload') {
                    state = 'paused';
                } else if (type === 'uploadFinished') {
                    state = 'done';
                }

            });

           
        });
    </script>


  
  
  
<%}
  else   //普通方式上传
  { %>
    <form name="upform" ID="upform" action="upload.ashx" method="post" enctype="multipart/form-data">
          <input type="file" name="file1" class="textbox">
          <input type="hidden" name="channelid" value="<%=channelId %>" />
          <input type="hidden" name="upBySwf" value="0" />
          <input type="hidden" name="fieldid" value="<%=fieldId %>"/>
          <input type="submit" value="确定上传" class="button"/>

         <%if (fieldId.ToLower().Equals("defaultpic"))
           {%>
          <label> <input type="checkbox" name="CreateThumbs" value="1"<%=CreateThumbs==1?" checked":string.Empty %>/>缩略图</label>
          <label> <input type="checkbox" name="AddWaterMark" value="1"<%=AddWaterMark==1?" checked":string.Empty %> />水印</label>
          <%
    } %>

         </form>

<%} %>
</body>
</html>
