zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Keepalived案例一:Keepalived双机热备(HA)精讲
    Linux服务器挂载ntfs移动硬盘
    RAC 单节点实例异常关闭,关键报错ORA--29770
    模拟等待事件:db file sequential read
    使用dbms_stats.gather_table_stats调整表的统计信息
    oracle rac常用的网络检查命令
    收集Oracle数据库中的SQL基线信息(一)基础信息收集
    Oracle 通过sql profile为sql语句加hint
    将指定SQL的执行计划从共享池删除的方法
    数据库什么时候建立索引?
  • 原文地址:https://www.cnblogs.com/PEPE/p/3670551.html
Copyright © 2011-2022 走看看