先上效果图。
在用之前呢,你得先更新最新版的layui版本。经验之谈_(:_」∠)_
今天在用的时候,实在是碰到太多的坑,本来是拒绝更新到最新版来着。
首先是layui.js和layui.all.js的问题。这个是什么问题呢!就是layui.js没有upload.render方法
_(:_」∠)_ _(:_」∠)_ _(:_」∠)_
于是就在百度搜索了:“layui.js is not found reder” 有答案说用layui.all.js
然后引用layui.all.js,而layui.all.js有render方法却不会触发<input type=file的上传功能。(吐血一波)( ̄ー ̄)
然后走神了下百度了 “layui.js和layui.all.js的区别” ,然后也不知道怎么回事,反正莫名其妙好了。
好的,那么我就继续往下。上传之后图片不预览出来。这是自己傻逼,被搞懵了,只是一个layuihide样式没删掉,又吐血一波(楼主最近补血嫌血多,多糖铁复合胶囊、生血宁片,你值得拥有)
就这么用了测试几回后.......打开windows的upload功能(其实就是<input type=file>打开的那个弹窗)没用了,回想起来可能是缓存还是怎么滴吧。哎呀,反正也不写废话了,中间的波折也就过了。
好,一个上午就这么没了。
下午上班,更新了最新版后。导入layui.js和 layui/lay/modules/upload.js(我也忘记有没有用了,反正就导了)完美,不会出现上午的问题了。人呐就是这么傻,能简单解决的非得找原因解决。
接下来是编写后台、写样式、js调试、添加删除按钮以及删除功能。layui图片上传是没用删除按钮的,除非是表格式的,不过区别也不大,只是不太好看。
编写传到mvc控制器的后台,emm
public class UploadFileController : MvcControllerBase { public ActionResult UploadImg() { string resultUrl = ""; for (int i = 0; i < Request.Files.Count; i++) { resultUrl += Upload(Request.Files[i]); if (i<Request.Files.Count-1) { resultUrl += ","; } } return Success("上传成功", resultUrl); } private string Upload(HttpPostedFileBase postedFile) { UploadFiles uf = new UploadFiles(); string filepath = "images\Goods\"; string path = GetMapPath(filepath);//UploadFile/images/goods/ if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var filelength = postedFile.ContentLength; string fileExt = GetPostfixStr(postedFile.FileName); var fileMaxSize = 307200; //300K var fileName = Guid.NewGuid() + "." + fileExt; //返回的上传后的文件名 string resultUrl = Config.GetValue("ServerIpHost") + "/UploadFile/images/Goods/" + fileName;//存入数据库的链接 if (filelength <= fileMaxSize) { byte[] buffer = new byte[filelength]; postedFile.InputStream.Read(buffer, 0, filelength); postedFile.SaveAs(path + fileName); } return resultUrl; } /// <summary> /// 获取文件格式名 /// </summary> /// <param name="filename"></param> /// <returns></returns> private string GetPostfixStr(string filename) { int start = filename.LastIndexOf("."); int length = filename.Length; string postfix = filename.Substring(start + 1); return postfix; } public string GetMapPath(string strPath) { if (System.Web.HttpContext.Current != null) { return System.Web.HttpContext.Current.Server.MapPath(strPath); } else //非web程序引用 { strPath = strPath.Replace("/", "\"); if (strPath.StartsWith("\")) { strPath = strPath.Substring(strPath.IndexOf('\', 1)).TrimStart('\'); } return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath); } } }
写了两个图片上传,一个是多图,一个是单图
layui.use(['form', 'upload', 'element'], function () { var form = layui.form , layer = layui.layer; var upload = layui.upload; var element = layui.element; var $ = layui.jquery; //拖拽上传 var uploadMain = upload.render({ elem: '#test10' , url: '/UploadFile/UploadImg' //改成您自己的上传接口 //, before: function (obj) {//上传前触发 // //预读本地文件示例,不支持ie8 // obj.preview(function (index, file, result) { // layui.$('#uploadDemoView').removeClass('layui-hide').find('img').attr('src', result); // //$('#demo2').attr('src', result); //图片链接(base64) // }); //} , choose: function (obj) {//选择后触发 var files = this.files = obj.pushFile(); var view = layui.$('#uploadDemoView'); //预读本地文件示例,不支持ie8 obj.preview(function (index, file, result) { var _html = $(['<div class="divimg" style="float:left;">' , '<img style="max- 196px;max-height:200px" id="viewImg' + index + '" alt="上传成功后渲染" src="' + result + '">' , '<div class="divX" >' , '<img src = "/Content/images/ui_close.png" width = "20" height = "20" />' , '</div>' , '</div>'].join('')); _html.find(".divX").on('click', function () { delete files[index]; //删除对应的文件 _html.remove(); uploadDetail.config.elem.next()[0].value = ''; }) layui.$('#uploadDemoView').removeClass('layui-hide'); view.removeClass('layui-hide'); _html.find(".divX").on('click', function () { delete files[index]; //删除对应的文件 _html.remove(); uploadDetail.config.elem.next()[0].value = ''; }) view.append(_html); }); } , auto: false//false将不触发before //, bindAction: "#uploadBtn" , size: 300//单位kb , done: function (data) { if (data.message != "") { layer.msg(data.message); } if (data.type == 1) { var fileUrl = data.resultdata; $("input[name='mainPic']").val(fileUrl); } else if (data.type == 3) { return false; } } , progress: function (n, elem) { var percent = n + '%' //获取进度百分比 element.progress('lodingdemo', percent); //可配合 layui 进度条元素使用 } }); var uploadDetail; //拖拽上传 uploadDetail = upload.render({ elem: '#upDiv2' , url: '/UploadFile/UploadImg' //改成您自己的上传接口 , choose: function (obj) {//选择图片后触发 var files = this.files = obj.pushFile();//每次会把新图片加入集合
//-----------------图片数量限制 var filecount = Object.getOwnPropertyNames(files).length;//这里就不说,做图片数量限制 if (filecount > 4) { layer.msg("只能上传4张"); var fileobj = Object.getOwnPropertyNames(files)// $(fileobj).each(function (i, j) {//删除本次添加的图片,不删的话 if (i > 3) { delete files[j]; } }) return false; }
//---------------------------- var view2 = layui.$('#uploadDemoView2'); //预读本地文件示例 obj.preview(function (index, file, result) { var _html = $(['<div class="divimg" style="float:left;">' , '<img style="max- 196px;max-height:200px" id="viewImg' + index + '" alt="上传成功后渲染" src="' + result + '">' , '<div class="divX" >' , '<img src = "/Content/images/ui_close.png" width = "20" height = "20" />' , '</div>' , '</div>'].join('')); view2.removeClass('layui-hide'); _html.find(".divX").on('click', function () { debugger; delete files[index]; //删除对应的文件 _html.remove(); uploadDetail.config.elem.next()[0].value = ''; }) view2.append(_html); }); } , multiple: true // , number: 4//这个是限制一次性选择4张图片 反正就不能用,没卵用 , auto: false//false将不触发before , size: 300//单位kb , done: function (data) { if (data.message != "") { layer.msg(data.message); } if (data.type == 1) { var fileUrl = data.resultdata; $("input[name='detailPic']").val(fileUrl); } else if (data.type == 3) { return false; } } //, error: function (index, upload) { // //当上传失败时,你可以生成一个“重新上传”的按钮,点击该按钮时,执行 upload() 方法即可实现重新上传 //} , progress: function (n, elem) { var percent = n + '%' //获取进度百分比 element.progress('lodingdemo2', percent); //可配合 layui 进度条元素使用 } }); $("#uploadBtn").click(function () { uploadMain.upload(); uploadDetail.upload(); return false; }) //自定义验证规则
//监听提交 //表单取值 });
<style type="text/css"> .divX { position: absolute; top: 0px; right: 0px; text-align: right; padding-right: 3px; z-index: 200; -moz-border-radius: 20px; -webkit-border-radius: 20px; line-height: 10px; font-weight: bold; cursor: pointer; font-size: 10px; } .divimg { max-height: 220px; height: 220px; width: 258px; max-width: 258px; background-color: #fff; border: 1px dashed #e6e6e6; position: relative; text-align: center; } .divimg > img { padding-top: 10px; } </style> <form class="layui-form layui-form-pane" lay-filter="example"> <input type="hidden" name="mainPic" /> <input type="hidden" name="detailPic" /> <div class="layui-form-item"> <button class="layui-btn layui-btn-normal layui-btn-radius" id="uploadBtn" lay-submit="">开始上传</button> </div> <div class="layui-form-item"> <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;"> <legend>上传主图(300kb内)</legend> </fieldset> <div class="layui-upload-drag" id="test10"> <div class="layui-progress" lay-filter="lodingdemo" lay-showpercent="true"> <div class="layui-progress-bar" lay-percent="0%"></div> </div> <i class="layui-icon">�</i> <p>点击上传,或将文件拖拽到此处</p> <hr /> </div> <div class="layui-hide" id="uploadDemoView"> @*<img style="max- 196px;max-height:200px" id="demo2" alt="上传成功后渲染" lay-filter="imgfilter" src=""> <div class="divX " onclick="del(this)"> <img src="~/Content/images/ui_close.png" width="20" height="20" /> </div>*@ </div> </div> <div class="layui-form-item"> <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;"> <legend>上传详情页(300kb内,最多4张)</legend> </fieldset> <div class="layui-upload-drag" id="upDiv2"> <div class="layui-progress" lay-filter="lodingdemo2" lay-showpercent="true"> <div class="layui-progress-bar" lay-percent="0%"></div> </div> <i class="layui-icon">�</i> <p>点击上传,或将文件拖拽到此处</p> <hr> </div> <div class="layui-hide" id="uploadDemoView2"> </div> </div> </form>