这个插件也不算是原创吧,毕竟基础代码是从网上下载来的,首先谢谢开始做这个控件的人。在这个基础上,我添加了一些功能,完善了下。
说明:
这个上传控件的前台是基于html 和javascript生成和处理的
后台是 c# .
效果图
通过点击 添加附件,就可以选择相应的文件并添加。现在的功能是指允许图片上传
代码分析:
//var path="UserControls/"//删除按钮路径 var inputCount = 1; //控件个数,实际上传数少一个, var Allupfiled = 0; //总共上传 var Endupfiled = 0; //已上传 var allowExtension = "" var ua = navigator.userAgent.toLowerCase(); //浏览器信息 var info = { ie: /msie/.test(ua) && !/opera/.test(ua), //匹配IE浏览器 op: /opera/.test(ua), //匹配Opera浏览器 sa: /version.*safari/.test(ua), //匹配Safari浏览器 ch: /chrome/.test(ua), //匹配Chrome浏览器 ff: /gecko/.test(ua) && !/webkit/.test(ua) //匹配Firefox浏览器 }; window.onload = SetClick; //加载完成,添加一个控件 function SetClick() { //if(inputCount>=10) //{ //alert("附件个数不能超过10个!"); //return; //} var container = document.getElementById("fileUpArea"); var input1 = document.createElement("input"); input1.type = "file"; //input1.name="file"+inputCount; input1.name = "filesupload"; input1.id = "file" + inputCount; input1.className = "fileinput"; input1.onchange = function (event) { if (this.value) { var k = this.value.lastIndexOf("\\"); var str = this.value.substring(k + 1); //判断上传文件类型 if (!CheckFileExtension(str)) return false; var divs = document.getElementById("filetxt").getElementsByTagName("div"); var check = false; for (var i = 0; i < divs.length; i++) { if (divs[i].innerHTML.indexOf(str) != -1) { check = true; break; } } if (!check) { Allupfiled++; SetIframeInput(this, inputCount, str); } else { alert("不允许添加同名附件!请重命名!"); return; } } } container.appendChild(input1); inputCount++; //input1.click(); } //这里可以动态去设定文件类型 function CheckFileExtension(str) { var extension = str.lastIndexOf("."); if (str.indexOf(".gif", extension) == -1 && str.indexOf(".jpg", extension) == -1 && str.indexOf(".png", extension) == -1) { alert("请选择gif或jpg或png的图象文件"); return false; } } function CheckFileNames(str) { var divs = document.getElementById("filetxt").getElementsByTagName("div"); var check = false; for (var i = 0; i < divs.length; i++) { if (/"+str"+/i.test(divs[i].innerHTML)) { check = true; break; } } } var WriteCookie = function (name, value, duration, path, domain, secure) { if (name == null || name == '') { throw ("name"); } var cookie = name + "=" + escape(value) + (duration ? "; expires=" + (new Date(new Date().getTime() + (duration * 3600000))).toUTCString() : "") + "; path=" + (path && path != '' ? path : "/") + (domain && domain != '' ? "; domain=" + domain : "") + (secure ? "; secure" : ""); document.cookie = cookie; }; var ReadCookie = function (name) { if (!name || name == '') { throw ("name"); } if (document.cookie.length > 0) { ix = document.cookie.indexOf(name + "="); if (ix > -1) { start = ix + name.length + 1; end = document.cookie.indexOf(";", start); if (end == -1) { end = document.cookie.length; } return unescape(document.cookie.substring(start, end)); } } return null; } function SetIframeInput(input, num, str)//选取值后的file控件,第几个,选取的文件名称 { var body = document.body; //页面body var name = input.id; //fileName var contxt = document.createElement("div"); //显示附件名称用的div var filetxtDiv = document.getElementById("filetxt"); //显示用的div(contxt)的上级div; var iframename = "iframe" + name; //框架iframe的名称 var iframe; //框架 var form = document.createElement('form'); //创建表单 var statediv = document.createElement("span"); //状态div var stopdiv = document.createElement("span"); //停止按钮 var jxupdiv; //上传按钮 var imgs = document.createElement('img'); //删除按钮 var upedfilename; //上传后文件名称 //var filedNames=document.getElementById("filedName");//显示上传后所有附件名称,后台取值用 var filedNames = getfiledName(); if (Endupfiled == 0) { filedNames.value = ""; } contxt.id = input.id + "text"; //显示用的div(contxt)的ID contxt.innerHTML = str + " "; //contxt的innerHTML(显示内容) contxt.className = ""; filetxtDiv.appendChild(contxt); //添加一个显示附件内容的div imgs.src = path + "images/f2.gif"; imgs.onclick = Dispose; //删除事件 contxt.appendChild(imgs); //添加删除按钮 statediv.id = "state" + num; statediv.className = "spanstate"; statediv.innerHTML = "准备上传"; contxt.appendChild(statediv); //添加状态div //创建iframe iframe = document.createElement(info.ie ? "<iframe name=\"" + iframename + "\">" : "iframe"); if (info.ie) { document.createElement("<iframe name=\"" + iframename + "\">"); } else { document.createElement("iframe"); } iframe.name = iframename; iframe.style.display = "none"; //插入body body.insertBefore(iframe, body.childNodes[0]); //设置form form.name = "form" + name; //表单名称 form.target = iframename; form.method = "post"; form.encoding = "multipart/form-data"; form.action = path + "Fileup.ashx?type=add"; //form.action="UserControls/CallBack.aspx"; body.insertBefore(form, body.childNodes[0]); //添加控件进form form.appendChild(input); SetClick(); //重新添加一个upfile控件 statediv.innerHTML = "正在上传"; //添加停止按钮 stopdiv.id = "stopdiv" + num; stopdiv.innerHTML = "停止"; stopdiv.style.cursor = "hand"; contxt.appendChild(stopdiv); stopdiv.onclick = function ()//停止事件 { iframe.src = path + "StopUpLoad.ashx"; //无任何处理代码 window.frames[iframename].location.reload(); //重新刷新iframe终止上传,在 iframe onload事件中处理 //iframe.location.reload(); } //定义iframe 的onload事件 if (info.ie)//IE 需要注册onload事件 { iframe.attachEvent("onload", CallBack); } else { iframe.onload = CallBack; } //提交 -------------------------------------------------- form.submit(); //提交完毕----------------------------------------------- function CallBack()//iframe加载完成,返回结果处理 { try { var value = iframe.contentWindow.document.body.innerHTML; upedfilename = value.substring(value.indexOf("@returnstart@") + 13, value.indexOf("@returnend@")); if (upedfilename.length > 3)//正常上传,返回上传后文件名 { //alert(upedfilename); finished(); } else//停止上传,从StopUpLoad.ashx页面返回空值,也可能是返回错误001,000 { if (upedfilename == "002") { alert("上传文件类型不正确"); } var parent = document.getElementById("filetxt"); parent.removeChild(statediv.parentNode); /*statediv.innerHTML="等待上传"; statediv.style.color="#008080"; continueUpLoad();//上传按钮*/ } } catch (msg) { statediv.innerHTML = "上传失败"; statediv.style.color = "#808080"; continueUpLoad(); //上传按钮 } } function continueUpLoad()//上传按钮 { stopdiv.style.visibility = "hidden"; jxupdiv = document.createElement("span"); //上传按钮 jxupdiv.id = "jxupdiv" + num; jxupdiv.innerHTML = "上传"; jxupdiv.style.cursor = "hand"; contxt.appendChild(jxupdiv); //添加上传按钮 jxupdiv.onclick = function ()//重新上传 { contxt.removeChild(jxupdiv); statediv.innerHTML = "正在上传"; statediv.style.color = "#0099FF"; stopdiv.style.visibility = "visible"; form.submit(); //重新提交 } } function Dispose()//删除事件 { //alert("ddd"); form.action = path + "Fileup.ashx?type=del"; form.submit(); filetxtDiv.removeChild(contxt); body.removeChild(form); body.removeChild(iframe); Allupfiled--; //总上传数减一 if (upedfilename) { if (upedfilename.length > 3) { Endupfiled--; if (upedfilename == filedNames.value) { filedNames.value = ""; } else if (filedNames.value.indexOf(upedfilename) == 0) { filedNames.value = filedNames.value.replace(upedfilename + ",", ""); } else { filedNames.value = filedNames.value.replace("," + upedfilename, ""); } } } } function finished()//上传完毕 { statediv.style.color = "#ff0000"; statediv.innerHTML = "上传成功"; contxt.removeChild(stopdiv); if (filedNames.value == "") { filedNames.value = upedfilename; } else { filedNames.value += "," + upedfilename; } Endupfiled++; //已上传数加一 } } function checkFileState() { if (Endupfiled != Allupfiled) { alert("还有文件未上传成功!"); return false; } return true; }
后台:
<%@ WebHandler Language="C#" Class="Fileup" Debug="true"%> using System; using System.Web; using System.IO; public class Fileup : IHttpHandler { public void ProcessRequest (HttpContext context) { string type = context.Request.QueryString["type"]; switch(type) { case "add": AddFile(context); break; case "del": DelFile(context); break; default: break; } } protected void DelFile(HttpContext context) { string filename = context.Request.Cookies.Get("filecookie").Value; string strFilePath = context.Server.MapPath("upfile/" + filename); if (File.Exists(strFilePath)) { File.Delete(strFilePath); } context.Request.Cookies.Remove("filecookie"); } protected bool CheckFile(string fileExtension) { string[] allowExtension = { ".jpg", ".gif",".png" }; bool fileOk = false; for (int i = 0; i < allowExtension.Length; i++) { if (fileExtension == allowExtension[i]) { fileOk = true; break; } } return fileOk; } protected void AddFile(HttpContext context) { string str1 = ""; string str2 = ""; string rvalue = ""; try { HttpFileCollection fileList = context.Request.Files; //HttpFileCollection fileList = HttpContext.Current.Request.Files; for (int i = 0; i < fileList.Count; i++) { HttpPostedFile hPostedFile = fileList[i]; string filename = ""; string filepath = ""; if (hPostedFile.ContentLength > 0 && hPostedFile.FileName.Length > 0) { //float zldx = hPostedFile.ContentLength / 1024; filename = hPostedFile.FileName; int k = filename.LastIndexOf("."); int j = filename.LastIndexOf("\\"); string type = filename.Substring(k); //filename = filename.Substring(j + 1, k - j - 1); filename = filename.Substring(j + 1); DateTime datetime1 = System.DateTime.Now; type = type.ToLower(); if (!CheckFile(type)) { rvalue = "002"; break; } filepath = datetime1.ToString("yyyyMMddHHmmss") + "." + type; HttpCookie filecookie = new HttpCookie("filecookie"); filecookie.Value = filepath; context.Response.Cookies.Add(filecookie); hPostedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath("upfile\\" + filepath)); if (str1 == "") str1 = filepath; else str1 += "," + filepath; if (str2 == "") { str2 += filename; } else str2 += "," + filename; } } if (str1.Length > 0) { //context.Response.Write(str1 + "&" + str2); rvalue = str1; } else { if (rvalue.Length == 0) { rvalue = "000"; } } } catch (Exception e) { rvalue = "001"; } context.Response.Expires = -1; context.Response.Clear(); context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); context.Response.ContentType = "text/plain"; //context.Response.Write("<script type='text/javascript'>parent.finish('" + rvalue + "');</script>"); context.Response.Write("@returnstart@" + rvalue + "@returnend@"); context.Response.End(); } public bool IsReusable { get { return false; } } }
原理: 通过生成<input type="file"> 控件 和 form表单,然后提交到后台,实现文件的上传。同样,删除也是。
具体代码下载