MVC5 - How to transfer file upload with model to controller using jquery ajax

I need to transfer my download file to my controller using jquery ajax.

JS:

$('#btnpopupreg').click(function () { $.ajax({ type: 'POST', url: '/Membership/Register', data: $('#frmRegister').serializeArray(), dataType: 'json', headers: fnGetToken(), beforeSend: function (xhr) { }, success: function (data) { //do something }, error: function (xhr) { } }) }) 

View:

 @model Test.RegisterViewModel @{ using Html.BeginForm(Nothing, Nothing, FormMethod.Post, New With {.id = "frmPopUpRegister", .enctype = "multipart/form-data"}) } <input type="file" /> //rest of my strongly typed model here <input type="button" value="BUTTON" /> //rest of the code here 

Controller:

 [HttpPost()] [AllowAnonymous()] [ValidateAntiForgeryToken()] public void Register(RegisterViewModel model) { if (Request.Files.Count > 0) { //always 0 } if (ModelState.IsValid) { //do something with model } } 

I can get the model value just fine, but Request.Files always returns null. I also tried using HttpPostedFileBase, but it also always returns null

 [HttpPost()] [AllowAnonymous()] [ValidateAntiForgeryToken()] public void Register(RegisterViewModel model, HttpPostedFileBase files) { //files always null if (ModelState.IsValid) { //do something with model } } 
+1
source share
2 answers

First you need to give you control over the a name file so that it can send back the value to your controller.

 <input type="file" name="files" /> // 

Then serialize your form and related files (s)

 var formdata = new FormData($('form').get(0)); 

and send a message using

 $.ajax({ url: '@Url.Action("Register", "Membership")', type: 'POST', data: formdata, processData: false, contentType: false, success: function (data) { .... } }); 

Please note that the file input must be inside the form tags

+3
source

You need to use FormData with a combination of the parameter contentType, processData and false:

  var formData = new FormData(); formData.append("userfile", $('#frmRegister input[type="file"]')[0].files[0]); // append the file in the form data $.ajax({ type: 'POST', url: '/Membership/Register', data: formdata, // send it here dataType: 'json', contentType:false, // this processData:false, // and this should be false in case of uploading files headers: fnGetToken(), beforeSend: function(xhr) { }, success: function(data) { //do something }, error: function(xhr) { } }) 
0
source

Source: https://habr.com/ru/post/1232264/


All Articles