MVC + ajaxform 文件上传
一、前端cshtml代码
<tr> <td width="130" align="right">添加附件:</td> @using (Html.BeginForm("FileUp", "Detail", FormMethod.Post, new { enctype = "multipart/form-data", id = "formFileUpload" })) { <td> <input name="file" type="file" value="浏览..." id="uploadFile" style="display: none;" /> <input type="text" class="fj_nr" id="filePath" /> </td> <td> <input type="button" value="浏览..." class="fh_btn" id="btnSee"> <input type="submit" value="上传" class="fh_btn" id="btnUploadFile" /> </td> } </tr> <tr id="attachMents"> </tr>
二、JS代码
(function () { var replyJs = replyJs || {}; replyJs.unitls = (function () { var controller = '/RenosData.Fax.Web/Detail'; var homeController = '/RenosData.Fax.Web/Home'; //传真回复 var replyFax = function () { //浏览附件 $("#btnSee").bind("click", function (e) { $("#uploadFile").click(); }); //上传附件 $("#uploadFile").bind("change", function (e) { $("#filePath").val($("#uploadFile").val()); }); $("#btnUploadFile").click(function () { addAttachment(); return false; }); //删除传真附件 $("#btnDelAttach").live("click",function () { $.ajax({ url: controller + '/DelAttachment', type: 'post', //dataType: 'json', data: "{file:'" + $(this).attr("filename") + "'}", contentType: 'application/json; charset=utf-8', success: function (data) { if (data.status == "success") { $("#attachMents").empty(); } else { alert(data.message); } }, error: function (err) { alert(err.toString()); } }); }); //发送传真 $("#btnSendFax").click(function () { addFaxToDb("send"); }); }; //上传附件 var addAttachment = function () { if (!$("#filePath").val()) { alert("请选择需要上传的文件!"); return; } //function showRequest(formData, jqForm, options) { // //alert('发送前'); // return true; //} //function showResponse(responseText, statusText) { // //alert('发送后'); //} //var options = { // //target: '#outputdiv', // beforeSubmit: showRequest, // success: showResponse //}; //$(this).ajaxSubmit(options); $("#formFileUpload").ajaxSubmit({ dataType: 'json', beforeSend: function (xhr) { }, success: function (data) { if (data) { if (data.message == "success") { $("#filePath").val(""); $("#attachMents").empty().append("<td width='130' align='right'>已上传附件:</td><td><label id='lblFileName'>" + data.fileOldName + "</label></td><td><input type='button' value='删除' class='fh_btn' id='btnDelAttach' filename='" + data.fileName + "' filesize='" + data.fileSize + "'></td>"); } else { alert(data.message); } } }, complete: function () { } }); return; }; //传真状态:发送or保存 var back = function () { window.history.go(-1); }; return { replyFax: replyFax, }; }()); $(function () { replyJs.unitls.replyFax(); }); })(jQuery);
三、Controller代码
/// <summary> /// 添加附件 /// </summary> /// <returns></returns> [HttpPost] public ActionResult FileUp() { HttpPostedFileBase uploadFile = Request.Files[0]; var fax = new FaxModel(); if (uploadFile == null || uploadFile.ContentLength == 0) { fax = new FaxModel() { Message = "请选择上传附件!", Attachment = null }; return Json(new { message = fax.Message }); } //if (uploadFile.ContentLength > 20971520) //{ // fax = new FaxModel() { Message = "请上传20MB以内的附件!", Attachment = null }; // return View("NewFax", fax); //} try { var newFileName = Guid.NewGuid() + "_" + uploadFile.FileName; ; string attachFilePath = WebConfig.Attachment; if (!Directory.Exists(attachFilePath)) Directory.CreateDirectory(attachFilePath); string filePath = Path.Combine(attachFilePath, newFileName); uploadFile.SaveAs(filePath); var attachment = new FileAttachmentModel() { FileName = newFileName, FileLength = (uploadFile.ContentLength * 1.0 / 1024).ToString("0.00"), FilePath = filePath, FileOldName = uploadFile.FileName, FileSize = uploadFile.ContentLength }; fax = new FaxModel() { Attachment = attachment }; ViewBag.FaxMsg = uploadFile.FileName; return Json(new { message = "success", fileOldName = attachment.FileOldName, fileSize = attachment.FileSize, fileName = attachment.FileName }); } catch (Exception) { return Json(string.Empty); } }
附件删除
/// <summary> /// 附件删除 /// </summary> /// <param name="file"></param> /// <returns></returns> [HttpPost] public ActionResult DelAttachment(string file) { try { string attachFilePath = WebConfig.Attachment; string filePath = Path.Combine(attachFilePath, file); if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); return Json(new { status = "success" }); } return Json(new { status = "false", message = "附件删除失败!" }); } catch (Exception ex) { return Json(new { status = "false", message = "附件删除失败!" }); } }
作者:PEPE
出处:http://pepe.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述