上传文件-layui+ashx
一、首先了解一下layui关于这个组件吧
文档说明:https://www.layui.com/doc/modules/upload.html
demo:https://www.layui.com/demo/upload.html
二、在我们项目中的应用
eaurl是往后台传参,是文件的存入服务器的路径,成功后会返回文件名,再将文件名存入库中
eaUrl = "~" + eaUrl.substring(1); //initUploadify("uploadify", "fileQueue"); layui.use('upload', function () { var $ = layui.jquery , upload = layui.upload; upload.render({ elem: '#filebtn' , url: '../LayuiUploadHandler.ashx' //上传接口 , accept: 'file' //普通文件 , data: { folder: eaUrl } , done: function (res) { if (res.msg != "") { alert(res.msg); layer.msg('上传成功'); $j("#<%=hfFiles.ClientID %>").val(res.msg); //ShowFiles($j("#fileDiv2"), queueID, eaUrl + new Date().getFullYear().toString()); } },error: function(index, upload){ layer.msg('上传出错'); } }); })
public class LayuiUploadHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { string newFileName = string.Empty; try { result ret = new result(); OilDigital.CGGL.BLL.LogService.LogOperationString("上传开始:"); context.Response.ContentType = "text/plain"; context.Response.Charset = "utf-8"; HttpPostedFile file = HttpContext.Current.Request.Files[0]; string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"]); if (file != null) { if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } newFileName = file.FileName; if (newFileName.LastIndexOf("\\") > -1) { newFileName = DateTime.Now.Ticks + "_" + newFileName.Substring(newFileName.LastIndexOf("\\") + 1); } else { newFileName = DateTime.Now.Ticks + "_" + newFileName; } file.SaveAs(uploadPath + newFileName); //下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失 //context.Response.Write(newFileName); ret.msg = newFileName; OilDigital.CGGL.BLL.LogService.LogOperationString("上传完成:"+ newFileName); } else { ret.msg = "上传文件失败"; //context.Response.Write(""); } context.Response.Write(new JavaScriptSerializer().Serialize(ret)); context.Response.End(); } catch (Exception ex) { throw new Exception("导入文件出错:" +ex.Message); } } public bool IsReusable { get { return false; } } } public class result { public result() { this.code = "200"; } public string code { get; set; } public string msg { get; set; } }
打广告:有需要微信投票、点赞、注册的朋友可以找我哦:18963948278