2016-11-17 40 views
1

我讀了一些不可能使用Ajax.BeginForm保存文件的文章。MVC5 Ajax.BeginForm上傳表單與文件

我有MVC5的形式使用Ajax.BeginForm,因此用戶無需刷新頁面一個很好的響應程序。

現在,需求是添加4個將保存文件(文件上傳)的字段。

也讀這也許與jquery.form.js這是可能的。

所以我的問題是關於另一種方法是這樣的任何意義:

  1. 形式保持Ajax.BeginForm
  2. 用戶將數據輸入到表格。
  3. 當用戶需要將文件加載到表單中時,我正在考慮將該文件上傳到服務器並暫時存儲在那裏。
    1. 當窗體被保存時,在服務器端我可以獲取臨時文件,然後保存它們。

這是否任何意義?欣賞已經面臨這種情況的人的任何建議。

+0

不能使用'Ajax.BeginForm()'上傳文件。但是,您可以用'$阿賈克斯()'和'FormData' - 參見[這個答案](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to- formdata-and-obtain-it-in-mvc/29293681#29293681)(但它有點不清楚爲什麼你要分開發布文件和表單數據) –

+0

@StephenMuecke謝謝,這意味着我可以上傳表單數據+上傳文件在同一時間使用$ .ajax和formdata? – VAAA

+0

當然 - '變種FORMDATA =新FORMDATA($( '形式')得到(0));'將您的序列化表單控件,包括文件輸入。您只需根據鏈接設置正確的ajax選項即可。 –

回答

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); 
 
     }

希望這將幫助你!

0

您無法使用MVC Ajax幫助程序進行文件上傳。 相反,你可以使用jquery form plugin,在一個正常的Html.BeginForm()

例子:

<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回調處理響應。

onComplete在AJAX完成後調用,如果您的參數爲console.log,您會看到它包含AJAX響應(json/html)。

嘗試這樣:

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

謝謝,雖然此方法工作,但您如何指定targetId和insertionMode.Replace,以便返回的partialView可以插入到特定的div中。 – Manish

+0

我編輯了答案。您必須手動處理AJAX響應。 – Catalin

0

添加此

$("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; 
     });