带文件的MVC5 Ajax.BeginForm上传表单

时间:2016-11-17 00:42:09

标签: asp.net-mvc jquery-forms-plugin ajax.beginform

我阅读了一些使用Ajax.BeginForm无法保存文件的文章。

我在MVC5中有一个使用Ajax.BeginForm的表单,因此用户可以在没有页面刷新的情况下使用响应良好的应用程序。

现在,要求添加4个将保存文件的字段(文件上传)。

也可以阅读jquery.form.js,这是可能的。

所以我的问题是关于其他方法,这是有道理的:

  1. 表单保留Ajax.BeginForm
  2. 用户在表单中输入数据。
  3. 当用户需要将文件加载到表单中时,我正在考虑将该文件即时上传到服务器并暂存。
    1. 保存表单后,在服务器端我可以获取临时文件,然后保存它们。
  4.   

    这有什么意义吗?感谢已经面临这种情况的人的任何建议。

3 个答案:

答案 0 :(得分:2)

请检查以下代码,以便单独保存表单数据文件上传

使用Ajax.BeginForm查看

@using (Ajax.BeginForm("", "", new AjaxOptions
{
    HttpMethod = "POST",
}, new { @id = "UploadFileForm", @class = "form-horizontal" }))
{
 <div class="col-sm-3">
            <label>Browse</label>
            <input type="file" id="file" name="file" />
            <p class="help-block">Supported format .doc,.docx,.pdf</p>
        </div>
        <div class="col-xs-12">
            <button type="button" value="Add" id="Addbtn" class="btn btn-primary">
                <i class="fa fa-plus-square"></i>&nbsp;Add
            </button>
        </div>
        }

文件上传按钮单击事件:

 $("#Addbtn").click(function () {
            // --- code for upload resume
            var formdata = new FormData();
            var getfile = document.getElementById('file');
            for (i = 0; i < getfile.files.length ; i++) {
                formdata.append(getfile.files[i].name, getfile.files[i]);
            }
            function isvalidFileFormat() {
                if (getfile.files.length > 0 ) {
                    var extention = $('#file').val().split('.');
                    var data;
                    $.each(extention, function (index, value) {
                        if (index == 1) {
                            data = value;
                        }
                    });

                    if (data == "pdf" || data == "docx" || data == "doc") {
                        return "";
                    }
                    else {
 return "<p>Please choose .pdf, .docx, .doc file only." + "</p>\n";
                    }
                }
                else 
                    return "";
                }
            }
            if (summary) { CustomAlert(summary); return false; } else {
                var TestModel = {
                    "Id": $("#hdnId").val()
                };
                $.ajax(
                 {
                 //Save Main Form Data
                     url: '/TestController/TestAction/',
                     type: "Post",
                     async: false,
                     dataType: "json",
                     data: JSON.stringify(TestModel), 
                     contentType: "application/json;charset=utf-8",
                     success: function (result) {
                     // After saving main data you can save this file for same user
                         formdata.append("Userid", result.id);
                         $.ajax({
                             url: '/TestController/Fileupload',
                             data: formdata,
                             contentType: false,
                             processData: false,
                             async: false,
                             type: 'POST',
                             success: function (data) {
                                 $("#YourDivName").html(data);
                             }
                         });
                         $("#file").val(null);
                     }
                 });
                return true;
            }
        });

以下是文件上传的代码

/// <summary>
        ///File Upload
        /// </summary>
        /// <param name="Userid"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Fileupload(int Userid = 0)
        {
            string path = string.Empty;
            string filename = string.Empty;
            string fileExtention = string.Empty;
            string withoutEXT = string.Empty;
            string ResumeFilePath = string.Empty;
            string ChangeFileName = string.Empty;
            bool uploadStatus = false;
            if (Request.Files != null && Request.Files.Count > 0)
            {

                for (int i = 0; i < Request.Files.Count; i++)
                {
                    HttpPostedFileBase file = Request.Files[i];
                    if (file.ContentType == "application/pdf" || file.ContentType == "text/rtf" || file.ContentType == "application/doc"
                        || file.ContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                    {
                        filename = Path.GetFileNameWithoutExtension(file.FileName);
                        fileExtention = Path.GetExtension(file.FileName);
                        withoutEXT = fileExtention.Replace(".", "");

                        ChangeFileName = filename + "_" + locationid + fileExtention;

                        var ifExistPath = "/Uploads/Files/" + ChangeFileName;
                        var FileVirtualPath = System.IO.Path.Combine(Server.MapPath("/Uploads/Files/"), ChangeFileName);
                        path = Path.Combine(Server.MapPath("~/Uploads/Files/"), ChangeFileName);

                        //delete file
                        
                        if (System.IO.File.Exists(path))
                        {
                            System.IO.File.Delete(path);
                        }
                        if (ifExistPath != FileVirtualPath)
                        {
                            file.SaveAs(path);
                            uploadStatus = true;
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Please upload a PDF or Doc or rtf File");
                        // return View("", model);
                    }
                    if (uploadStatus && path != string.Empty)
                    {

                        ResumeFilePath = "/Uploads/Files/";
                    //Add code for save this file in database here 
                    }
                }
            }
            return PartialView("Test", objMaster);
        }

希望这会对你有所帮助!!

答案 1 :(得分:1)

您无法在上传文件时使用MVC Ajax帮助程序。 相反,您可以使用普通Html.BeginForm()上的jquery form plugin

示例:

<form id="myForm" url="/Home/Upload" method="post" enctype="multipart/form-data">
    <label>File</label>
    <input name="file" type="file" />
</form>

<script>
    function bindAjaxForm(selector, onComplete, beforeSerialize) {
        var form = $(selector);
        $.validator.unobtrusive.parse(selector);
        form.data("validator").settings.submitHandler = function (frm) {
            $(frm).ajaxSubmit({
                beforeSerialize: function ($form, options) {
                    if (typeof (beforeSerialize) === "function") {
                        beforeSerialize($form, options);
                    }
                },
                complete: function (response, statusText) {
                    if (typeof onComplete === "function") {
                        onComplete(response, statusText);
                    }
                }
            });
        }
    };

    bindAjaxForm("#myForm", function(data, status) {
        alert("complete");
        console.log(arguments);
    });
</script>

您使用onCompletebeforeSerialize回调来处理响应。

在AJAX完成后调用

onComplete,如果你console.log它的参数,你会看到它包含AJAX响应(json / html)。

尝试这样的事情:

bindAjaxForm("#myForm", function(data, status) {
    $("#container").html(data);
});

答案 2 :(得分:1)

添加此

  $("body").on("submit", "#frmAddProduct", function (e) {
            var form = e.target;
            if (form.dataset.ajax) {
                e.preventDefault();
                e.stopImmediatePropagation();
                var xhr = new XMLHttpRequest();
                xhr.open(form.method, form.action);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        if (form.dataset.ajaxUpdate) {
                            var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
                        }
                    }
                };
                if ($("#frmAddProduct").valid()) { xhr.send(new FormData(form)); }
            } return true;
        });