今天给大家分享采用AspNet MVC+前端框架LayUi实现文件上传功能,感兴趣的朋友可以学习一下。
文件上传实体(UploadFile.cs)
public class UploadFile { public int code { get; set; } //请求code public string msg { get; set; } // 请求消息 public string src { get; set; } //文件路径 public string filename { get; set; } //原始文件名 }
前端代码(Upload.cshtml):
@{ Layout = null;}<!DOCTYPE html><html><head> <meta name="viewport" content="width=device-width" /> <title>文件上传示例</title> <link href="~/Content/lib/layui/css/layui.css" rel="stylesheet" /> <link href="~/Content/css/common.css" rel="stylesheet" /> <script src="~/Content/lib/layui/layui.js"></script></head><body> <div> <div class="layui-input-inline layui-btn-container" style="width: auto;"> <button type="button" class="layui-btn layui-btn-primary" id="btnUpload"> <i class="layui-icon"></i>上传附件 </button> <div id="layer-photos-demo" class="fr"> <img id="imgPhoto" style="height:100px;width:100px;" src="" alt=""> </div> </div> <div> <table class="layui-table"> <colgroup> <col width="150"> <col width="200"> </colgroup> <thead> <tr> <th>文件名称</th> <th>操作</th> </tr> </thead> <tbody id="uploadList"></tbody> </table> </div> </div> <script type="text/javascript"> layui.use(["upload"], function () {
var upload = layui.upload; var $ = layui.$; upload.render({ elem: '#btnUpload', url: '/Upload/UploadFile', size: '2048',//文件大小2M exts: 'png|gif|jpg|jpeg|zip|rar',//文件扩展名 done: function (res) { if (res.code == 0) { $("#imgPhoto").attr("src", res.src); $("#uploadList").append("<tr><td>" + res.filename + "</td><td><a target='_blank' href='" + res.src + "'>查看</a></td><tr>"); } } });
});</script></body></html>
控制器代码(UploadController.cs)
// 上传视图 public ActionResult Upload(){ return View(); } // 上传逻辑public JsonResult UploadFile() { UploadFile uploadFile = new UploadFile(); try { var file = Request.Files[0]; //获取选中文件 var filecombin = file.FileName.Split('.'); if (file == null || string.IsNullOrEmpty( file.FileName) || file.ContentLength == 0 || filecombin.Length < 2) { uploadFile.code = -1; uploadFile.src = ""; uploadFile.msg = "上传失败!请检查文件"; return Json(uploadFile, JsonRequestBehavior.AllowGet); } //定义本地路径位置 string localPath = Server.MapPath("~/Upload"); string filePathName = string.Empty; //最终文件名 string dateStr = DateTime.Now. ToString("yyyyMMddHHmmss"); filePathName = dateStr + "." + filecombin[1]; //Upload不存在则创建文件夹 if (!System.IO.Directory.Exists(localPath)) { System.IO.Directory.CreateDirectory(localPath); } //保存图片 file.SaveAs(Path.Combine(localPath, filePathName)); uploadFile.code = 0;
uploadFile.filename = filecombin[1]; uploadFile.src = Path.Combine("/Upload/", filePathName); uploadFile.msg = "上传成功"; return Json(uploadFile, JsonRequestBehavior.AllowGet); } catch (Exception) { uploadFile.code = -1; uploadFile.src = ""; uploadFile.msg = "上传失败!"; return Json(uploadFile, JsonRequestBehavior.AllowGet); } }