一丶上传案例one
1.页面html
1 <div> 2 <form id="j_editForm" method="post"> 3 <table class="align-center"> 4 <tr> 5 <td>图片:</td> 6 <td> 7 <img class="j_upLoad" /> 8 <input name="j_file" hidden type="file" /> 9 <input type="hidden" name="sealPhotoUrl" class="easyui-validatebox" id="j_ImgUrl" /> 10 <input type="hidden" name="id" /> 11 </td> 12 </tr> 13 </table> 14 </form> 15 </div>
2.js封装
1 (function (w) { 2 var mainUtil = { 3 //初始化方法 4 Init: function () { 5 this.InitTapEvent(); 6 }, 7 InitTapEvent: function () { 8 specificUtil.envetInit(); 9 }, 10 }; 11 12 //封装具体实现对象 13 var specificUtil = { 14 envetInit: function () { 15 //一些点击事件 16 $(".j_upLoad").on("click", function () { 17 return $(this).next().trigger("click"); 18 }); 19 20 $("input[name=‘j_file‘]").on("change", function () { 21 var f = this.files[0]; 22 //这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件 23 if (!/image\/\w+/.test(f.type)) { 24 $.messager.alert("提示", ‘请确保文件为图像类型‘, "info"); 25 return false; 26 } 27 //判断大小 28 var size = f.size; 29 if (size / 1024 / 1024 > 4) { 30 $.messager.alert("提示", ‘请上传小于4M的图片‘, "info"); 31 return false; 32 } 33 //获取地址 34 var formFile = new FormData(); 35 //formFile.append("action", "UploadVMKImagePath"); 36 formFile.append("file", f); //加入文件对象 37 otherUtil.upLoad(formFile, this); 38 }); 39 40 $("#j_pwd").on("change", function () { 41 $("input[name=‘sealPwd‘]").val($(this).val()); 42 }) 43 } 44 }; 45 var otherUtil = { 46 //封装页面公共方法 47 upLoad: function (formFile, that) { 48 $.ajax({ 49 url: "/PaperPrint_Areas/PaperPrint/Upload", 50 type: ‘POST‘, 51 data: formFile, 52 dataType: "json", 53 cache: false,//上传文件无需缓存 54 processData: false,//用于对data参数进行序列化处理 这里必须false 55 contentType: false, //必须 56 success: function (data) { 57 $.procAjaxMsg(data, function () { 58 $.alertMsg(data.Msg, ‘操作提示‘, function () { 59 $(that).prev().attr("src", data.BackUrl); 60 $(that).next().val(data.BackUrl); 61 }); 62 }, function () { 63 $.alertMsg(data.Msg, ‘操作提示‘, null); 64 }); 65 } 66 }) 67 } 68 }; 69 70 w.mainUtil = mainUtil; 71 72 })(window) 73 74 75 76 $(function () { 77 mainUtil.Init(); 78 });
3.接口处理
1 public ActionResult Upload() 2 { 3 try 4 { 5 if (Request.Files.Count == 0) 6 { 7 //var objData = new { BackUrl = "", Data = "", Msg = "图片上传失败", Statu = "error" }; 8 //return Json(objData); 9 return PackagingAjaxmsg(new AjaxMsgModel { BackUrl = null, Data = null, Msg = "图片上传失败", Statu = AjaxStatu.err }); 10 } 11 else 12 { 13 //得到上传的图片 14 var file = Request.Files[0]; 15 //要保存的文件路径 16 var path = Path.Combine(Server.MapPath(Request.ApplicationPath), "Upload", "Image1"); 17 if (!Directory.Exists(path)) 18 { 19 Directory.CreateDirectory(path); 20 } 21 //要保存的文件名称 22 string fileName = string.Format("{0}_{1}{2}", oc.CurrentUser.uId, DateTime.Now.ToString("yyyyMMddHHmmss"), Path.GetExtension(file.FileName)); 23 //保存文件到指定的目录 24 file.SaveAs(Path.Combine(path, fileName)); 25 //上传之后图片的相对路径 26 string relativePath = Path.Combine(Request.ApplicationPath, "Upload", "Image1", fileName); 27 //var objData = new { BackUrl = relativePath, Data = "", Msg = "上传成功", Statu = "ok" }; 28 //return Json(objData); 29 return PackagingAjaxmsg(new AjaxMsgModel { BackUrl = relativePath, Data = null, Msg = "上传成功", Statu = AjaxStatu.ok }); 30 } 31 } 32 catch (Exception ex) 33 { 34 Common.Log.LogHelper.Info(ex.Message); 35 //var objData = new { BackUrl = "", Data = "", Msg = "图片上传失败", Statu ="error" }; 36 //return Json(objData); 37 return PackagingAjaxmsg(new AjaxMsgModel { BackUrl = null, Data = null, Msg = "图片上传失败", Statu = AjaxStatu.err }); 38 } 39 }
二丶上传案例two
1.页面html
1 <div> 2 <img src="@sealPhotoUrl" id="j_imgShow" class="img-show"/> 3 <input id="j_upLoad" hidden type="file" /> 4 <input type="hidden" name="sealPhotoUrl" class="easyui-validatebox" id="j_ImgUrl" value="@sealPhotoUrl" /> 5 </div>
2.js
1 (function (w) { 2 //一:封装对象 3 var mainUtil = { 4 //初始化方法 5 Init: function () { 6 this.InitUtil(); 7 this.InitTapEvent(); 8 this.initEvent(); 9 }, 10 InitUtil: function () { 11 12 }, 13 //初始化事件 14 initEvent: function () { 15 //1.初始化事件 16 pageUtil.UpLoadFile(); 17 18 }, 19 //初始化点击事件 20 InitTapEvent: function () { 21 $("#j_btn").on("click", function () { 22 $.messager.confirm(‘操作提示‘, ‘确定要保存吗‘, function (result) { 23 var f = $("#j_SelfAddForm"); 24 if (result) { 25 $.ajax({ 26 type: ‘POST‘, 27 url: ‘/FlowDesign_Areas/PersonalSealInfo/EditPersonalSeal‘, 28 data: myUitls.serializeObject(f), 29 dataType: ‘json‘, 30 cache: false, 31 success: function (jsonData) { 32 myUitls.procAjaxMsg(jsonData, function () { 33 myUitls.alertMsg(jsonData.Msg, ‘提示‘, null); 34 //取消确定按钮聚焦效果 35 myUitls.cancleFocus(); 36 }, function () { 37 $(‘#j_message‘).html("温馨提示:" + jsonData.Msg); 38 }); 39 } 40 }); 41 42 } 43 }) 44 45 }) 46 47 48 }, 49 50 }; 51 //二:封装页面信息获取 52 var pageUtil = { 53 //上传文件 54 UpLoadFile: function () { 55 $("#j_upLoad").uploadify({ 56 buttonText: ‘‘, 57 buttonClass: "", 58 height: 170, 59 width: 300, 60 cancelImg: ‘‘, 61 swf: ‘/Content/js/lib/uploadify/uploadify.swf‘, 62 uploader: ‘/FlowDesign_Areas/PersonalSealInfo/Upload‘,//通过后台的程序把文件上传到服务器 63 multi: false,//是否允许同时选择多个文件 64 fileSizeLimit: ‘20MB‘,//文件大小 65 fileTypeExts: ‘*.jpg;*.png;*.jpeg;*.bmp;*.gif‘,//可选文件的扩展名 66 formData: { 67 ‘folder‘: ‘/Upload‘, 68 ‘ASPSESSID‘: ASPSESSID, 69 ‘AUTHID‘: auth//测试 70 }, 71 overrideEvents: [‘onSelectError‘, ‘onUploadSuccess‘, ‘onDialogClose‘, ‘onUploadError‘], 72 onUploadProgress: function (file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) { 73 var bar = $.messager.progress(‘bar‘); 74 bar.progressbar(‘setValue‘, Math.round(bytesUploaded / bytesTotal * 10000) / 100.00) 75 76 }, 77 onUploadSuccess: function (file, data, response) { 78 79 $.messager.progress(‘close‘); 80 81 var jsonData = $.parseJSON(data); 82 myUitls.procAjaxMsg(jsonData, function () { 83 $("#j_imgShow").attr("src", jsonData.BackUrl); 84 $("#j_ImgUrl").val(jsonData.BackUrl); 85 //上传成功,温馨提示制空 86 $("#j_message").html(""); 87 myUitls.alertMsg(jsonData.Msg, ‘提示‘, null); 88 //取消确定按钮聚焦效果 89 myUitls.cancleFocus(); 90 }, function () { 91 myUitls.alertMsg(jsonData.Msg, ‘操作提示‘, null); 92 //取消确定按钮聚焦效果 93 myUitls.cancleFocus(); 94 }); 95 }, 96 onUploadError: function (file, errorCode, errorMsg, errorString) { 97 98 $.messager.progress(‘close‘); 99 100 var filename = file.name; 101 if (filename.length > 10) { 102 filename = filename.substr(0, 9) + "..."; 103 } 104 myUitls.alertMsg(‘文件【‘ + filename + ‘】上传失败‘, ‘上传失败‘, null); 105 //取消确定按钮聚焦效果 106 myUitls.cancleFocus(); 107 }, 108 onSelectError: function (file, errorCode, errorMsg, errorString) { 109 var filename = file.name; 110 if (filename.length > 10) { 111 filename = filename.substr(0, 9) + "..."; 112 } 113 switch (errorCode) { 114 case -110: 115 myUitls.alertMsg(‘文件【‘ + filename + ‘】大小超出系统限制 ‘, ‘上传失败‘, null); 116 //取消确定按钮聚焦效果 117 myUitls.cancleFocus(); 118 break; 119 case -130: 120 myUitls.alertMsg(‘文件【‘ + filename + ‘】不能被上传 ‘, ‘上传失败‘, null); 121 //取消确定按钮聚焦效果 122 myUitls.cancleFocus(); 123 break; 124 } 125 return false; 126 }, 127 onSelect: function (file, errorCode, errorMsg) { 128 129 $.messager.progress({ 130 title: "上传进度", 131 interval: 5000 132 }); 133 134 }, 135 136 }); 137 $("#j_upLoad-button").hide(); 138 $("#j_upLoad-queue").hide(); 139 $("#j_upLoad").css("margin-top", ‘-173px‘); 140 $("#SWFUpload_0").css("margin-left", ‘1px‘); 141 } 142 }; 143 w.mainUtil = mainUtil; 144 145 })(window) 146 147 148 149 $(function () { 150 mainUtil.Init(); 151 });
3.接口处理
1 public ActionResult Upload(string fileName) 2 { 3 try 4 { 5 //未加载到要上传的印章图片 6 if (Request.Files.Count == 0) 7 { 8 return PackagingAjaxmsg(new AjaxMsgModel { BackUrl = null, Data = null, Msg = "未找到要上传的图片", Statu = AjaxStatu.err }); 9 } 10 else 11 { 12 //1.图片保存路径 13 var nowTime = DateTime.Now; 14 string timeStr = nowTime.ToString("HH0011"); 15 string objFilePath = Server.MapPath("~/Upload\\Seal_Image\\") + nowTime.ToString("yyyy-MM-dd") + "\\" + oc.CurrentUser.id + "\\" + timeStr + "\\"; 16 if (!Directory.Exists(objFilePath)) 17 { 18 Directory.CreateDirectory(objFilePath); 19 } 20 //2.得到上传的文件 21 var file = Request.Files[0]; 22 23 fileName = fileName.Replace("#", "井").Replace("&", "_").Replace("%", "_"); ; 24 //判断是否存在存在就删除 25 var routeName = objFilePath + fileName; 26 //3.要保存文件 27 FileInfo fileInfo = new FileInfo(routeName); 28 while (fileInfo.Exists) 29 { 30 nowTime = DateTime.Now; 31 timeStr = nowTime.ToString("HHffff"); 32 objFilePath = Server.MapPath("~/Upload\\Seal_Image\\") + nowTime.ToString("yyyy-MM-dd") + "\\" + oc.CurrentUser.id + "\\" + timeStr + "\\"; 33 if (!Directory.Exists(objFilePath)) 34 { 35 Directory.CreateDirectory(objFilePath); 36 } 37 routeName = objFilePath + fileName; 38 fileInfo = new FileInfo(routeName); 39 } 40 41 file.SaveAs(routeName); 42 file.InputStream.Close(); 43 string fileRelativeUrl = @"/Upload\\Seal_Image\\" + nowTime.ToString("yyyy-MM-dd") + @"\\" + oc.CurrentUser.id + @"\\" + timeStr + @"\\" + fileName; 44 //返回数据 45 return PackagingAjaxmsg(new AjaxMsgModel { BackUrl = fileRelativeUrl, Data = null, Msg = "上传成功", Statu = AjaxStatu.ok }); 46 } 47 } 48 catch (Exception ex) 49 { 50 Common.Log.LogHelper.Info(ex.Message); 51 return PackagingAjaxmsg(new AjaxMsgModel { BackUrl = null, Data = null, Msg = "图片上传失败", Statu = AjaxStatu.err }); 52 } 53 }
原文:https://www.cnblogs.com/chenze-Index/p/9517812.html