⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 uploadhandler.cs

📁 一个超强的在线WORD汉化版ASP程序5...
💻 CS
字号:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.IO;
using System.Text;
using Lion.Data.Library.HtmlEditor;

using Lion.IO.SharpZIP.Checksums;
using Lion.IO.SharpZIP.Zip;
using Lion.IO.SharpZIP.GZip;

namespace Lion.Data.Library.HtmlEditor.Core
{
	/// <summary>
	/// UpLoad 的摘要说明。
	/// </summary>
	internal class UpLoadHandler
	{
		private string sType, sStyleName;
		//设置变量
		private string sAllowExt, nAllowSize, sUploadDir, nAutoDir, sBaseUrl, sContentPath;
		//接口变量
		private string sFileExt, sOriginalFileName, sSaveFileName, sPathFileName;

		#region Function Custom

		/// <summary>
		/// 初始化系统信息
		/// </summary>
		public void initSystem(HttpContext context)
		{
			InitPara(context);
			if((context.Request.QueryString["action"]!=null))
			{
				if(context.Request.QueryString["action"].Trim().ToUpper()=="REMOTE")
				{
					DoRemote(context);
				}
				else if(context.Request.QueryString["action"]=="save")
				{
					ShowForm(context);
					DoSave(context);
				}
				else
				{
					ShowForm(context);
				}
			}
			else
			{
				ShowForm(context);
			}
			
		}

		/// <summary>
		/// 自动获取远程文件
		/// </summary>
		/// <param name="context"></param>
		private void DoRemote(HttpContext context)
		{
			string sContent;
			sContent = context.Request.Form["LionSky_HtmlEditor_UploadText"];
			if(sAllowExt!=String.Empty)
			{
				sContent = ReplaceRemoteUrl(sContent, sAllowExt);
			}
			context.Response.Write("<HTML><HEAD><TITLE>远程上传</TITLE><meta http-equiv='Content-Type' content='text/html; charset=gb2312'></head><body><input type=hidden id=UploadText value=\""+ sContent.Replace("&","&amp;").Replace("<","&lt;").Replace(">","&gt;").Replace("\"","&quot;") +"\"></body></html>");

			OutScriptNoBack("parent.setHTML(UploadText.value);try{parent.addUploadFile('" + sOriginalFileName + "', '" + sSaveFileName + "', '" + sPathFileName + "');} catch(e){} parent.remoteUploadOK();");
		}

		/// <summary>
		/// 替换字符串中的远程文件为本地文件并保存远程文件
		/// </summary>
		/// <param name="sHTML">要替换的字符串</param>
		/// <param name="sExt">执行替换的扩展名</param>
		/// <returns></returns>
		private string ReplaceRemoteUrl(string sHTML,string sExt)
		{
			string s_Content = sHTML;
			System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(sHTML,@"((http|https|ftp|rtsp|mms):(\/\/|\\\\){1}(([A-Za-z0-9_-])+[.]){1,}(net|com|cn|org|cc|tv|[0-9]{1,3})(\S*\/)((\S)+[.]{1}(gif|jpg|jpeg|bmp)))",System.Text.RegularExpressions.RegexOptions.IgnoreCase);
			string[] a_RemoteUrl = new string[mc.Count];
			//转入无重复数据
			for(int i=0;i<mc.Count;i++)
			{				
				a_RemoteUrl[i] = (mc[i].Groups[0].ToString());				
			}
			
			//开始替换操作
			string SaveFileName, SaveFileType;

			//上传文件自动建目录标志
			string path = (nAutoDir=="0"?"":(nAutoDir=="1"?DateTime.Now.Year.ToString():(nAutoDir=="2"?(DateTime.Now.Year.ToString()+"-"+DateTime.Now.Month.ToString("00")):(nAutoDir=="3"?(DateTime.Now.Year.ToString()+"-"+DateTime.Now.Month.ToString("00")+"-"+DateTime.Now.Day.ToString("00")):""))))+"/";

			
			sOriginalFileName = sOriginalFileName + "|";
			sSaveFileName = sSaveFileName + "|";
			sPathFileName = sPathFileName + "|";
			foreach(string str in a_RemoteUrl)
			{				
				SaveFileType = str.Substring(str.LastIndexOf(".")+1).ToLower();
				SaveFileName = GetRndFileName(SaveFileType);				
				if(SaveRemoteFile(SaveFileName, str))
				{
					sOriginalFileName += str.Substring(str.LastIndexOf("/")+1)+"|";
					sSaveFileName += SaveFileName+"|";
					sPathFileName += sContentPath + path + SaveFileName+"|";
					s_Content = s_Content.Replace(str, sContentPath + path + SaveFileName);
				}
			}
			sOriginalFileName = sOriginalFileName.Substring(0,sOriginalFileName.Length-1);
			sSaveFileName = sSaveFileName.Substring(0,sSaveFileName.Length-1);
			sPathFileName = sPathFileName.Substring(0,sPathFileName.Length-1);
			return s_Content;
		}

		/// <summary>
		/// 保存远程的文件到本地
		/// </summary>
		/// <param name="s_LocalFileName">本地文件名</param>
		/// <param name="s_RemoteFileUrl">远程文件URL</param>
		/// <returns></returns>
		private bool SaveRemoteFile(string s_LocalFileName, string s_RemoteFileUrl)
		{
			

			System.Net.WebClient wc = new System.Net.WebClient();
				
			byte[] buff = wc.DownloadData(s_RemoteFileUrl);
			if(buff.Length==0)
			{
				return false;
			}
			if(buff.Length/1024>int.Parse(nAllowSize))
			{
				return false;
			}
			else
			{				
				//上传文件自动建目录标志
				string path = (nAutoDir=="0"?"":(nAutoDir=="1"?DateTime.Now.Year.ToString():(nAutoDir=="2"?(DateTime.Now.Year.ToString()+"-"+DateTime.Now.Month.ToString("00")):(nAutoDir=="3"?(DateTime.Now.Year.ToString()+"-"+DateTime.Now.Month.ToString("00")+"-"+DateTime.Now.Day.ToString("00")):""))))+"/";
				//如果不存在建立目录
				if(!Directory.Exists(Helper.Context.Server.MapPath(sUploadDir)+path))Directory.CreateDirectory(Helper.Context.Server.MapPath(sUploadDir)+path);	

				System.IO.FileStream fs = new System.IO.FileStream(Helper.Context.Server.MapPath(sUploadDir + path + s_LocalFileName),System.IO.FileMode.Create,System.IO.FileAccess.Write);
			
				fs.Write(buff,0,buff.Length);
				fs.Close();
				return true;
			}
		}

		private void ShowForm(HttpContext context)
		{
			if((context.Request.QueryString["action"]!=null))
			{
				if(context.Request.QueryString["action"]=="remote")
				{
					return;
				}
			}
			
			System.Text.StringBuilder Sb = Helper.GetScript("/UpLoad.txt");
			string Argument = context.Request.QueryString["configfile"];
			Sb.Replace("{configfile}",Argument);
			Sb.Replace("{sType}",sType);
			Sb.Replace("{sStyleName}",sStyleName);
			Sb.Replace("{sAllowExt}",sAllowExt);
			context.Response.Expires=0;
			context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
			context.Response.ContentEncoding = Encoding.UTF8;
			context.Response.ContentType="text/html";
			context.Response.Clear();
			context.Response.Write(Sb.ToString());
			Sb.Remove(0,Sb.Length);				
		}

		/// <summary>
		/// 文件上传
		/// </summary>
		/// <param name="postedFile"></param>
		private void UploadFile(HttpPostedFile postedFile)
		{
			if(postedFile.ContentLength<=0)
			{
				OutScript("parent.UploadError('请选择有效的上传文件!')",Helper.Context);
				return;
			}
			if(postedFile.ContentLength/1024>int.Parse(nAllowSize))
			{
				OutScript("parent.UploadError('你上传的文件总大小超出了最大限制(" + nAllowSize + "KB)!')",Helper.Context);
				return;
			}
			//上传源文件全名称
			sOriginalFileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf("\\")+1);
			//上传文件扩展名
			sFileExt = sOriginalFileName.Substring(sOriginalFileName.LastIndexOf(".")+1).ToLower();
			//随机文件名
			sSaveFileName = GetRndFileName(sFileExt);	
			//检测扩展名的有效性
			if(!CheckValidExt(sFileExt))
			{					
				return;
			}

			//上传文件自动建目录标志
			string path = (nAutoDir=="0"?"":(nAutoDir=="1"?DateTime.Now.Year.ToString():(nAutoDir=="2"?(DateTime.Now.Year.ToString()+"-"+DateTime.Now.Month.ToString("00")):(nAutoDir=="3"?(DateTime.Now.Year.ToString()+"-"+DateTime.Now.Month.ToString("00")+"-"+DateTime.Now.Day.ToString("00")):""))))+"/";
			//如果不存在建立目录
			if(!Directory.Exists(Helper.Context.Server.MapPath(sUploadDir)+path))Directory.CreateDirectory(Helper.Context.Server.MapPath(sUploadDir)+path);
			//文件保存路径+目录
			string pathname = Helper.Context.Server.MapPath(sUploadDir + path + GetRndFileName("zip"));  
			//对文件进行压缩
			System.IO.FileStream ZipFile = System.IO.File.Create(pathname);
			ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
			ZipEntry ZipEntry = new ZipEntry("Lion.Data.Library.HtmlEditor.File");
			ZipStream.PutNextEntry(ZipEntry);
			ZipStream.SetLevel(6);
			byte[] buffer = new byte[4096];
			System.Int32 size =postedFile.InputStream.Read(buffer,0,buffer.Length);
			ZipStream.Write(buffer,0,size);
			try 
			{
				while (size < postedFile.InputStream.Length) 
				{
					int sizeRead =postedFile.InputStream.Read(buffer,0,buffer.Length);
					ZipStream.Write(buffer,0,sizeRead);
					size += sizeRead;
				}
			} 
			catch(System.Exception ex)
			{
				OutScript("parent.UploadError('"+ ex.ToString() +"')",Helper.Context);
				return;
			}
			ZipStream.Finish();
			ZipStream.Close();
			postedFile.InputStream.Close();

			//对文件进行解压
			ZipInputStream s = new ZipInputStream(System.IO.File.OpenRead(pathname));
			ZipEntry theEntry;
			while ((theEntry = s.GetNextEntry()) != null) 
			{				
				//解压文件到指定的目录
				FileStream streamWriter = File.Create(Helper.Context.Server.MapPath(sUploadDir + path + sSaveFileName));    
				int fsize = 2048;
				byte[] data = new byte[2048];
				while (true) 
				{
					fsize = s.Read(data, 0, data.Length);
					if (fsize > 0) 
					{
						streamWriter.Write(data, 0, fsize);
					} 
					else 
					{
						break;
					}
				}    
				streamWriter.Close();
			}
			s.Close();
			System.IO.File.Delete(pathname);
			sPathFileName = sContentPath + path + sSaveFileName;			
			#endregion
		}

		/// <summary>
		/// 保存操作
		/// </summary>
		private void DoSave(HttpContext context)
		{			
			HttpFileCollection files  = context.Request.Files;				
			if(files.Count==0)
			{
				OutScript("parent.UploadError('请选择有效的上传文件!')",context);
				return;
			}
			UploadFile(files[0]);				
				
			//原文件名、保存后的文件名、保存后的路径文件名
			OutScript("parent.UploadSaved('" + sPathFileName + "');var obj=parent.dialogArguments.dialogArguments;if (!obj) obj=parent.dialogArguments;try{obj.addUploadFile('" + sOriginalFileName + "', '" + sSaveFileName + "', '" + sPathFileName + "');} catch(e){}",context);			
		}

		/// <summary>
		/// 初始化输入参数
		/// </summary>
		private void InitPara(HttpContext context)
		{
			if((context.Request.QueryString["type"]!=null))
			{
				sType = context.Request.QueryString["type"].ToUpper();
			}
			else
			{
				OutScript("parent.UploadError('无效的类型ID号,请通过页面上的链接进行操作!')",context);
				return;
			}
			
			sStyleName = ((context.Request.QueryString["style"]!=null)?context.Request.QueryString["style"]:"standard");
			if(Helper.GetStyleNode(sStyleName)!=null)
			{
				System.Xml.XmlNode node = Helper.GetStyleNode(sStyleName);
				sBaseUrl = node.SelectSingleNode("S_BaseUrl").InnerText;
				nAutoDir = node.SelectSingleNode("S_AutoDir").InnerText;
				sUploadDir = node.SelectSingleNode("S_UploadDir").InnerText;
				sUploadDir = sUploadDir.EndsWith("/")?sUploadDir:sUploadDir+"/";

				
				sContentPath = node.SelectSingleNode("S_ContentPath").InnerText;
				if(sBaseUrl=="1")
				{
					sContentPath = Helper.RelativePath2RootPath(sUploadDir);
				}
				else if(sBaseUrl=="2")
				{
					sContentPath = Helper.RootPath2DomainPath(sUploadDir);
				}				
				
				switch(sType)
				{
					case "REMOTE":
						sAllowExt = node.SelectSingleNode("S_RemoteExt").InnerText;
						nAllowSize = node.SelectSingleNode("S_RemoteSize").InnerText;
						break;
					case "FILE":
						sAllowExt = node.SelectSingleNode("S_FileExt").InnerText;
						nAllowSize = node.SelectSingleNode("S_FileSize").InnerText;
						break;
					case "MEDIA":
						sAllowExt = node.SelectSingleNode("S_MediaExt").InnerText;
						nAllowSize = node.SelectSingleNode("S_MediaSize").InnerText;
						break;
					case "FLASH":
						sAllowExt = node.SelectSingleNode("S_FlashExt").InnerText;
						nAllowSize = node.SelectSingleNode("S_FlashSize").InnerText;
						break;
					default:
						sAllowExt = node.SelectSingleNode("S_ImageExt").InnerText;
						nAllowSize = node.SelectSingleNode("S_ImageSize").InnerText;
						break;
				}
			}
			else
			{
				OutScript("parent.UploadError('无效的样式ID号,请通过页面上的链接进行操作!')",context);
				return;
			}			
		}

		/// <summary>
		/// 输出客户端脚本
		/// </summary>
		/// <param name="msg">脚本消息</param>
		/// <param name="context">请求的HTTP特定信息</param>
		private void OutScript(string msg,HttpContext context)
		{
			context.Response.Write("<script language=javascript>" + msg + ";history.back()</script>");
		}

		/// <summary>
		/// 输出客户端脚本
		/// </summary>
		/// <param name="msg">脚本消息</param>
		private void OutScriptNoBack(string msg)
		{
			Helper.Context.Response.Write("<script language=javascript>" + msg + "</script>");
		}

		/// <summary>
		/// 取随机文件名
		/// </summary>
		/// <param name="sExt">文件名扩展名</param>
		/// <returns></returns>
		private string GetRndFileName(string sExt)
		{
			return(DateTime.Now.Year.ToString()+DateTime.Now.Month.ToString("00")+DateTime.Now.Day.ToString("00")+DateTime.Now.Hour.ToString("00")+DateTime.Now.Minute.ToString("00")+DateTime.Now.Second.ToString("00")+Helper.GetRandomNext(4)+"."+sExt);	
		}

		/// <summary>
		/// 检测扩展名的有效性
		/// </summary>
		/// <param name="sExt">文件名扩展名</param>
		/// <returns></returns>
		private bool CheckValidExt(string sExt)
		{
			string[] aExt = sAllowExt.Split('|');
			bool flag=false;
			foreach(string filetype in aExt)
			{
				if(filetype.ToLower()==sFileExt)
				{
					flag = true;
					break;
				}
			}
			if(!flag)
			{
				OutScript("parent.UploadError('提示:\n\n请选择一个有效的文件,\n支持的格式有("+sAllowExt+")!')",Helper.Context);				
			}	
			return flag;
		}

		#endregion
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -