使用layui上传文件
使用layui上传文件
前端:
<div class="layui-upload"> <label class="layui-form-label" style="width:110px;">批量导入:</label> <button type="button" class="layui-btn layui-btn-normal" id="test8">选择文件</button> <button type="button" class="layui-btn" id="test9">开始上传</button> </div> <script type="text/javascript"> layui.use('upload', function () { var $ = layui.jquery,upload = layui.upload; upload.render({ elem: '#test8', url: '/UnbindMarking/upload', accept: 'file', acceptMime: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', auto: false, bindAction: '#test9', done: function (res) { console.log(res); }, error: function (index, upload) { console.log(index+upload); } }); }) </script>
后端:(C#代码)
主要是用HttpRequest来获取上传的文件
public string upload() { HttpRequest request = System.Web.HttpContext.Current.Request; if (request.Files.Count == 0) { return "{\"result\":\"false\",\"msg\":\"上传的文件不能为空!\"}"; } var file = request.Files[0]; var filePath = System.Web.HttpContext.Current.Server.MapPath("~/Files/"); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } file.SaveAs(filePath + file.FileName); return "{\"result\":\"true\",\"msg\":\"文件上传成功!\"}"; }