<%@ Page Language="C#" AutoEventWireup="true" Inherits="Kesion.NET.WebSite.UserUpload1" Codebehind="Upload.aspx.cs" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="Kesion.Cache" %>
<%@ Import Namespace="Kesion.Publics" %>
<%@ Import Namespace="Kesion.BLL" %>
<%@ Import Namespace="Kesion.Components" %>
<%@ Import Namespace="Kesion.XML" %>
<%@ Import Namespace="Kesion.Config" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html>
<html>
<head runat="server">
    <title>上传</title>
     <link href="/sysimg/user/css.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>
<script runat="server">
    int upBySwf = 1;  //启用swfupload上传 1 启用 0不启用
    ModelInfo __info = null;
    string fieldId = "-1";
    int formId = Utils.StrToInt(KSCMS.S("formid"));
    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 = 18;
    protected void Page_Load(object sender, EventArgs e)
    {


        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 (!string.IsNullOrEmpty(KSCMS.S("fieldid")))
        {
            fieldId = KSCMS.S("fieldid");
        }

        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

            }
        }
        if (channelId == 10002) CreateThumbs = 0;
        #region 读配置文件
        module = KSCMS.S("module");
        if (!string.IsNullOrEmpty(module))
        {
            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



        #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)  //用swfupload 
  {
     %>
      <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() == "affix")
            {
                Kesion.Components.BlogConfigInfo __configinfo = Kesion.Config.BlogConfigManage.Deserialize(Server.MapPath("~/config/plus/plus.space/Blog.config"));
                string fileSite = __configinfo.BlogArticleFileSize;
                string fileExt = __configinfo.BlogArticleFileExt;
		 %>
          var limitSize=<%=fileSite%>;
          var fileExt="<%=Utils.getSwfUploadExt(fileExt) %>" //限制扩展名

          <%}else if (fieldId.ToLower()=="defaultpic" || isPic==1){
		 %>
		 	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==10002){ //自定义表单
            if (formId==0){
             KSCMS.Die("error");
            }else{
             FormInfo __info = FormManage.GetFormSubjectInfo(formId);
             if (__info==null){
             KSCMS.Die("error");
             }else{
             ArrayList al = new ArrayList();
             al = XmlObject.GetSubElementByAttributeFromStr(__info.FieldsXML, "field", "@name", fieldId.Split('_')[0]);
            %>
		 	var limitSize=<%=Utils.StrToInt(al[7].ToString())%>; //限制大小 KB
			var fileExt="<%=Utils.getSwfUploadExt(al[6].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> 
              <%} %>
		  </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: {
                       "username": "<%=new TemporaryVar().UserName %>", "password": "<%=new TemporaryVar().PassWord %>", "CreateThumbs": 1, "ChannelID": 2, "AutoRename": 4, "addwatermark": "1", "fieldid": "-1", "upbyswf": 1
                    } 
            <%}else {%>
                    formData: {
                        "username":"<%=new TemporaryVar().UserName %>","password":"<%=new TemporaryVar().PassWord %>","upBySwf":1,UpType:"<%=UpType%>",module:"<%=module%>",ChannelID:<%=channelId%>,"FieldID":"<%=fieldId%>","formid":<%=formId%>,
                        "ispic":<%=isPic%>,
                        "AutoRename":4,
                        "AddWaterMark":<%=AddWaterMark%>,
                        "CreateThumbs":<%=CreateThumbs%>
                        <%if (isPic==1){ %>,"AddWaterMark":1,"CreateThumbs":1<%} %>
                    } 
                <%}%>
                ,
              <%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) {
            var $li = $('#' + file.id),
            $percent = $li.find('.progress .progress-bar');

            // 避免重复创建
            if (!$percent.length) {
                    $percent = $('<div class="progress progress-striped active">' +
                      '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                      '</div>' +
                    '</div>').appendTo($li).find('.progress-bar');
            }

                $li.find('p.state').text('上传中').hide();
            console.log(percentage)
                $percent.css('width', percentage * 100 + '%');
        });

        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);  //下载的软件
					     <%}
					     }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() == "affix")
                  {%>
				    $(function(){
				        $("input[affix='affixed']", window.parent.document).val(serverData);
				        $(".txtuploadfile2", window.parent.document).val(file.size + "," + file.type + "," + file.name);
				        $("input[affix='affixed']", window.parent.document).focus();
				        $("div[affix='divaffixed']", window.parent.document).html(serverData);
				        $(".txtuploadfile2", window.parent.document).focus();
				        console.info(file);
				    });
				 
				  <%}else{%>
				     if (serverData.indexOf('@')==-1){
				      parent.document.getElementById('<%=fieldId%>').value=serverData;
				     }else{
				        var d=serverData.split('@');
				        parent.document.getElementById('DefaultPic').value=d[1];
					    parent.insertHTMLToEditor('<img src="'+d[0]+'" />');
					 }
				 <%} 
            } %>

           // $('#' + 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>
		  <%if (ConfigManage.GetConfig().WaterMarkStatus!=0){ %>   
          <label> <input type="checkbox" name="AddWaterMark" value="1"<%=AddWaterMark==1?" checked":string.Empty %> />水印</label>
		  <%}%>
          <%
    } %>

         </form>

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