先看效果:
由于需要把保存到文件夹文件的路径、文件名等回传给界面,所以需要一个类,专门负责回传给客户端所需要的信息。
public class UploadFileResult { public string FileName { get; set; } public int Length { get; set; } public string Type { get; set; } public bool IsValid { get; set; } public string Message { get; set; } public string FilePath { get; set; } }
把上传的文件名改成以时间命名的格式,并保存到文件夹,再把回传信息以json形式传递给视图。关于删除,需要接收来自视图的文件名参数。
#region 上传单个文件 //显示 public ActionResult Index() { return View(); } //接收上传 [HttpPost] public ActionResult UploadFile() { List<UploadFileResult> results = new List<UploadFileResult>(); foreach (string file in Request.Files) { HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase; if (hpf.ContentLength == 0 || hpf == null) { continue; } var fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + hpf.FileName.Substring(hpf.FileName.LastIndexOf('.')); string pathForSaving = Server.MapPath("~/AjaxUpload"); if (this.CreateFolderIfNeeded(pathForSaving)) { hpf.SaveAs(Path.Combine(pathForSaving, fileName)); results.Add(new UploadFileResult() { FilePath = Url.Content(String.Format("~/AjaxUpload/{0}", fileName)), FileName = fileName, IsValid = true, Length = hpf.ContentLength, Message = "上传成功", Type = hpf.ContentType }); } } return Json(new { name = results[0].FileName, type = results[0].Type, size = string.Format("{0} bytes", results[0].Length), path = results[0].FilePath, msg = results[0].Message }); } #region 共用方法 /// <summary> /// 检查是否要创建上传文件夹,如果没有就创建 /// </summary> /// <param name="path">路径</param> /// <returns></returns> private bool CreateFolderIfNeeded(string path) { bool result = true; if (!Directory.Exists(path)) { try { Directory.CreateDirectory(path); } catch (Exception) { //TODO:处理异常 result = false; } } return result; } //根据文件名称删除文件 [HttpPost] public ActionResult DeleteFileByName(string name) { string pathForSaving = Server.MapPath("~/AjaxUpload"); System.IO.File.Delete(Path.Combine(pathForSaving, name)); return Json(new { msg = true }); } #endregion
前台视图主要做如下几件事:
由于表格行是动态生成的,需要对删除按钮以"冒泡"的方式注册事件: $('#tb').on("click", ".delImg", function ()
<html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <link href="~/Content/JSAjaxFileUploader/JQuery.JSAjaxFileUploader.css" rel="external nofollow" rel="stylesheet" /> <script src="~/Scripts/jquery-1.10.2.js"></script> <script src="~/Scripts/JSAjaxFileUploader/JQuery.JSAjaxFileUploaderSingle.js"></script> <style type="text/css"> #tb table{ border-collapse: collapse; width: 600px; } #tb td { text-align: center; padding-top: 5px; width: 25%; } #tb tr { background-color: #E3E3E3; line-height: 35px; } .showImg { width: 50px; height: 50px; } </style> <script type="text/javascript"> $(function () { //隐藏显示图片的表格 $('#tbl').hide(); $('#testId').JSAjaxFileUploader({ uploadUrl: '@Url.Action("UploadFile","Home")', inputText: '选择上传文件', //fileName: 'photo', maxFileSize: 512, //Max 500 KB file 1kb=1024字节 allowExt: 'gif|jpg|jpeg|png', zoomPreview: false, zoomWidth: 360, zoomHeight: 360, beforesend: function (file) { if ($('.imgName').text() != "") { deleteImg(); $('#tbl').hide(); } }, success: function (data) { $('.file_name').html(data.name); $('.file_type').html(data.type); $('.file_size').html(data.size); $('.file_path').html(data.path); $('.file_msg').html(data.msg); createTableTr(); $('#tbl').show(); $('.showImg').attr("src", data.path); $('.imgName').text(data.name); }, error: function (data) { alert(data.msg); } }); //点击删除链接删除刚上传图片 $('#tbl').on("click", ".delImg", function () { deleteImg(); //window.location.reload(); }); }); //删除图片方法:点击删除链接或上传新图片删除原先图片用到 function deleteImg() { $.ajax({ cache: false, url: '@Url.Action("DeleteFileByName", "Home")', type: "POST", data: { name: $('.imgName').text() }, success: function (data) { if (data.msg) { //alert("图片删除成功"); $('.delImg').parent().parent().remove(); } }, error: function (jqXhr, textStatus, errorThrown) { alert("出错了 '" + jqXhr.status + "' (状态: '" + textStatus + "', 错误为: '" + errorThrown + "')"); } }); } //创建表格 function createTableTr() { var table = $('#tbl'); table.append("<tr><td><img class='showImg'/></td><td colspan='2'><span class='imgName'></span></td><td><a class='delImg' href='javascript:void(0)'>删除</a></td></tr>"); } </script> </head> <body> <div id="testId"></div> <div id="tb"> <table id="tbl"> <tbody> </tbody> </table> </div> <div class="file_name"></div> <br /> <div class="file_type"></div> <br /> <div class="file_size"></div> <br /> <div class="file_path"></div> <br /> <div class="file_msg"></div> </body> </html>
另外:需要删除源js文件中input元素的multiple属性,使之只能接收单个文件。
本篇源码在github
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接