ajaxfileupload 上传使用demo
1.添加js引用
<script src="JS/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="JS/ajaxfileupload.js" type="text/javascript"></script>
2.html页面代码
1 <fieldset> 2 <legend><strong>项目申报附件</strong></legend> 3 <div style="width: 100%;"> 4 <a style="margin-left: 78%" href="../../ToSaveExcel/Help/预算编制项目相关上报范本文档.zip" target="_blank">点击查看上报范本</a> 5 <%-- <a href="../../ToSaveExcel/Yrzxsl/Silverlight.rar" target="_blank">点击下载添加附件安装程序</a>--%> 6 <img alt="新增附件" onclick="addfiletable()" style="cursor:pointer" src="../../Images/ImgButton/xzfj.gif"/> 7 </div> 8 9 <table cellpadding="5" cellspacing="0" width="100%" style="border-collapse: collapse; 10 margin-top: 6px;" id="Bz_file_talbe" class="shenpi"> 11 <thead> 12 <tr> 13 <th style="width: 50px;"> 14 序号 15 </th> 16 <th> 17 附件名称 18 </th> 19 <th style="width: 300px;"> 20 文件 21 </th> 22 <th style="width: 200px;"> 23 备注 24 </th> 25 <th style="width: 100px;"> 26 操作 27 </th> 28 </tr> 29 </thead> 30 <tbody> 31 </tbody> 32 </table> 33 <input type="hidden" id="hideFileNames"/> 34 </fieldset>
3.js代码
1 function addfiletable() { 2 var length = $("#Bz_file_talbe tbody tr").length; 3 var id = parseInt(parseInt(length) + 1); 4 var html = ' <tr>' + 5 '<td style="width:40px;"><input type="hidden" value="' + id + '" />' + id + '</td>' + 6 '<td> <input type="text" name="file_name" style="width: 90%;" /></td>' + 7 '<td style="width:300px;">' + getuploadhtml(id) + '</td>' + 8 '<td style="width:200px;"><input type="text" id="file_remark" style="width: 150px;" /></td>' + 9 '<td><a href="javascript:void(0)" onclick="SaveFiled(this)">[保存]</a> <a href="javascript:void(0)" onclick="delbudgetfile(this)">[删除]</a></td>' + 10 '</tr>'; 11 $("#Bz_file_talbe tbody").append(html); 12 13 }
1 function SaveFiled(obj) { 2 var tr = $(obj).parent().parent(); 3 var id = tr.find("td:eq(0) input").val(); 4 var filename = tr.find("td:eq(1) input").val(); 5 var filepath = $("#hideFileNames").val(); 6 var remark = tr.find("td:eq(3) input").val(); 7 if (filename == "") { 8 AlertMsg('附件名称不能为空!'); 9 return; 10 11 } 12 if (filepath == "") { 13 AlertMsg('附件上传异常,请重新上传!'); 14 return; 15 } 16 tr.find("td:eq(1)").empty().html('<span>' + filename + '</span>'); 17 tr.find("td:eq(2)").empty().html('<input type="hidden" id="tab_hdfilename" value="' + filepath + '" />' + getorginfilename(filepath)); 18 tr.find("td:eq(3)").empty().html('<span>' + remark + '</span>'); 19 tr.find("td:eq(4)").empty().html('<a href="javascript:void(0)" onclick="downbudgetfile(this)">[下载]</a> <a href="javascript:void(0)" onclick="delbudgetfile(this)">[删除]</a>'); 20 21 }
1 function delbudgetfile(obj) { 2 var tr = $(obj).parent().parent(); 3 var id = tr.find("td:eq(0) input").val(); 4 tr.remove(); 5 6 } 7 function getuploadhtml(id) { 8 return '<div style="margin-left:20px;">' + 9 '<div style="position:relative;width:270px;height:30px;background:#fff;border:1px solid #eee;">' + 10 '<input type="text" style="position:absolute;left:0;top:0;width:80%;height:100%;z-index:1; border:none; background:#fff;" id= "importPicName'+id+'" /> <img src="../../Images/attach.png" style="float:right; height:30px; width:30px;" />' + 11 '<input type ="file" id="ImportPicInput'+id+'" name= "myfile" onchange="f_onchangeinput(this)" style="position:absolute;left:0;top:0;width:100%;height:100%;z-index:999;opacity:0;-ms-filter: \'alpha(opacity=0)";\' /> '+ 12 '</div> '+ 13 '</div>'; 14 } 15 function downbudgetfile(obj) { 16 var tr = $(obj).parent().parent(); 17 var path = tr.find("td:eq(2) input").val(); 18 $.ajax({ 19 url: "../HandlerFiles/downFiles.ashx?type=IsExistsFile&fn=" + encodeURI(path) + "&t=" + new Date().getTime(), 20 async: false, 21 success: function(data) { 22 if (data == "1") { 23 $("#isexistsfile").val("1"); 24 } 25 else { 26 $("#isexistsfile").val("0"); 27 AlertMsg('服务器上该文件已被删除或不存在!'); 28 } 29 } 30 }); 31 if ($("#isexistsfile").val() == "1") { 32 $("#comdownshow").attr("src", "../HandlerFiles/downFiles.ashx?type=DownFile&fn=" + encodeURI(path)) + "&t=" + new Date().getTime(); 33 } 34 } 35 function getorginfilename(strfile) { 36 var filename = ""; 37 if (strfile != "") { 38 filename = strfile.substr(strfile.indexOf(',') + 1).replace(';', ''); 39 } 40 return filename; 41 }
上传代码:
1 function f_onchangeinput(obj) { 2 var id = $(obj).attr("id").replace("ImportPicInput", ""); 3 $("#importPicName" + id).val($(obj).val()); 4 $.ajaxFileUpload({ 5 type: "POST", 6 url: "/Common2/HandlerFiles/downFiles.ashx?type=UpLoad", 7 data: { "nmae": "sulin" }, //要传到后台的参数,没有可以不写 8 secureuri: false, //是否启用安全提交,默认为false 9 fileElementId: $(obj).attr("id"), //文件选择框的id属性 10 11 dataType: 'json', //服务器返回的格式 12 async: false, 13 success: function(data) { 14 if (data.status == '1') { 15 document.getElementById("hideFileNames").value = data.msg; 16 } else { 17 18 document.getElementById("hideFileNames").value = ""; 19 20 } 21 }, 22 error: function(data, status, e) { 23 24 } 25 }); 26 }
4.后端代码
1 public void UpLoad(HttpContext context) 2 { 3 HttpPostedFile file = context.Request.Files["myfile"]; 4 string name = context.Request["nmae"].ToString(); 5 string uploadPath = 6 HttpContext.Current.Server.MapPath("~/upload/");//uploadfile/ 7 //这里可以加验证 8 if (file != null && file.ContentLength > 0) 9 { 10 if (!Directory.Exists(uploadPath)) 11 { 12 Directory.CreateDirectory(uploadPath); 13 } 14 //var c = IsAllowedExtension(file); 15 //验证后缀名称 16 if (IsAllowExtension(file)) 17 { 18 //上传文件类型 19 string ContentType = file.ContentType; 20 int a = file.FileName.LastIndexOf("\\") + 1; 21 int b = file.FileName.LastIndexOf("."); 22 string fileName = file.FileName.Substring(a, b - a ); 23 string suffix = file.FileName.Substring(file.FileName.LastIndexOf(".") + 1);//上传文件后缀名 24 //上传文件大小 25 int filesize = file.ContentLength; 26 //生成上传文件名称 27 //string FileName = fileName.Replace(suffix, "") + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff"); 28 string FileName = Guid.NewGuid().ToString() + "," + fileName.Replace(suffix, ""); 29 string newFileName = FileName + "." + suffix; 30 file.SaveAs(uploadPath + newFileName); 31 string json = JsonConvert.SerializeObject(new { status = 1, msg = newFileName }); 32 context.Response.Write(json); 33 } 34 else 35 { 36 string json = JsonConvert.SerializeObject(new { status = 0, msg = "上传文件类型不允许" }); 37 context.Response.Write(json); 38 } 39 } 40 else 41 { 42 string json = JsonConvert.SerializeObject(new { status = 0, msg = "NO" }); 43 context.Response.Write(json); 44 } 45 } 46 47 /// <summary> 48 /// 验证后缀名 49 /// </summary> 50 /// <returns></returns> 51 public bool IsAllowExtension(HttpPostedFile filename) 52 { 53 if (filename != null) 54 { 55 string suffix = filename.FileName.Substring(filename.FileName.LastIndexOf(".")); 56 List<string> listextension = new List<string> { 57 ".xls",".xlsx",".doc",".docx",".pdf",".jpg",".gif","",".bmp",".png" 58 }; 59 if (listextension.Contains(suffix.ToLower())) return true; 60 } 61 return false; 62 63 64 } 65 public static bool IsAllowedExtension(HttpPostedFile file) 66 { 67 BinaryReader reader = new BinaryReader(file.InputStream); 68 69 Dictionary<string, string> diclist = new Dictionary<string, string> { 70 71 {"208207","doc|xls|ppt|wps"}, 72 {"8075","docx|pptx|xlsx|zip"}, 73 {"108101","txt"}, 74 {"8297","rar"}, 75 {"7790","exe"}, 76 {"3780","pdf"}, 77 {"6033","htm|html"}, 78 {"255216","jpg"}, 79 {"7173","gif"}, 80 {"13780","png"}, 81 {"6677","bmp"}, 82 {"64101","bat"} 83 }; 84 string fileclass = ""; 85 try 86 { 87 for (int i = 0; i < 2; i++) 88 { 89 fileclass += reader.ReadByte().ToString(); 90 } 91 } 92 catch (Exception) 93 { 94 throw; 95 } 96 if (diclist.ContainsKey(fileclass)) 97 { 98 return true; 99 } 100 else 101 { 102 return false; 103 } 104 }
5.效果图