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 = "附件删除失败!" });
            }
        }

ajaxForm.js

原文地址:https://www.cnblogs.com/PEPE/p/3670551.html