Answered by:
jquery ajax Upload file and data in the same POST

Question
-
User-921158202 posted
hi ,
i am trying to to send regular data model with a file upload on the same post method :
var file1 = $("#file-1")[0].files[0];
var formData = new FormData();
formData.append("files", file1);
let tpperson = {
"id": selectedstudent,
"fname": $("#fnameinput").val(),
"lastname": $("#lnameinput").val(),
"user": $("#userinput").val(),
"pass": $("#passinput").val(),
"photo" : formData
};$.post({
url: "/Admin/AddEditStudent",
contentType: "application/json; charset=utf-8",
async: false,
processData : false,
data: tpperson ,
async: false,success: function (response) {
},failure: function (errMsg) {
alert(errMsg); //errorMessage is id of the div
}
});
server side
public class person
{
public int id { get; set; }
public string fname { get; set; }
public string lastname { get; set; }
public string user { get; set; }
public string pass { get; set; }
public IList<IFormFile> photo { get; set; }
}
public string AddEditStudent( [FromBody] person st)
{
.....
}but st is always null
if i remove the [fromBody] there is a st variable but all fields are nullany help is welcome , thanks
Thursday, April 25, 2019 1:37 PM
Answers
-
User475983607 posted
Basic example.
[HttpGet] public IActionResult Index() { return View(); } [HttpPost] public async Task<IActionResult> Index(IFormFile Image, string FirstName) { // full path to file in temp location var filePath = Path.GetTempFileName(); using (var stream = new FileStream(filePath, FileMode.Create)) { await Image.CopyToAsync(stream); } return Ok(new { filePath, FirstName }); } }
@model MvcApi22.Models.FileUploadVm @{ ViewData["Title"] = "Index"; } <h1>Index</h1> <h4>FileUploadVm</h4> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="Index"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="FirstName" class="control-label"></label> <input asp-for="FirstName" class="form-control" /> <span asp-validation-for="FirstName" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Image" class="control-label"></label> <input type="file" name="Image" id="Image" multiple /> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" id="submit" /> </div> </form> </div> </div> @section scripts{ <script> $('#submit').click(function (e) { e.preventDefault(); var formData = new FormData(); var fileInput = $('#Image')[0].files[0]; formData.append("FirstName", $('#FirstName').val()); formData.append("Image", fileInput); $.ajax({ method: "post", url: '@Url.Action("Index")', data: formData, processData: false, contentType: false, success: function (response) { console.log(response); } }); }); </script> }
or
public class FileUploadVm { public string FirstName { get; set; } public IFormFile Image { get; set; } }
[HttpPost] public async Task<IActionResult> Index(FileUploadVm vm) { // full path to file in temp location var filePath = Path.GetTempFileName(); using (var stream = new FileStream(filePath, FileMode.Create)) { await vm.Image.CopyToAsync(stream); } return Ok(new { filePath, vm.FirstName }); }
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Thursday, April 25, 2019 3:55 PM
All replies
-
User475983607 posted
You are not using FormData correctly. The fields should be added to the FormData object.
ContentType is not needed if you are submitting a standard form.
contentType: "application/json; charset=utf-8",
Consider writing asynchronous JavaScript rather synchronous.
async: false,
FormData References
https://developer.mozilla.org/en-US/docs/Web/API/FormData
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
Thursday, April 25, 2019 1:53 PM -
User-921158202 posted
ok i have changed the code to this :
var file1 = $("#file-1")[0].files[0];
var formData = new FormData();
formData.append("id", $("#PersonId").val());
formData.append("fname", $("#fnameinput").val());
formData.append("lastname", $("#lnameinput").val());
formData.append("user", $("#userinput").val());
formData.append("pass", $("#passinput").val());
formData.append("photo", file1);
$.post({
url: "/Admin/AddEditStudent",
cache: false,
contentType: false,
processData: false,
data: formData,
success: function (response) {
},
failure: function (errMsg) {
}
});
Server Side
[HttpPost]
public string AddEditStudent( FormCollection st)
{
var r = "";
r = "test";
retrn r;
}
but i get a code 500 error in the console with no other information
and the debugger cannot attach to the breakpoint i have put in the server side code
btw i am using visual studio code with asp.net core mvc 2.1 .
Thursday, April 25, 2019 2:44 PM -
User475983607 posted
Basic example.
[HttpGet] public IActionResult Index() { return View(); } [HttpPost] public async Task<IActionResult> Index(IFormFile Image, string FirstName) { // full path to file in temp location var filePath = Path.GetTempFileName(); using (var stream = new FileStream(filePath, FileMode.Create)) { await Image.CopyToAsync(stream); } return Ok(new { filePath, FirstName }); } }
@model MvcApi22.Models.FileUploadVm @{ ViewData["Title"] = "Index"; } <h1>Index</h1> <h4>FileUploadVm</h4> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="Index"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="FirstName" class="control-label"></label> <input asp-for="FirstName" class="form-control" /> <span asp-validation-for="FirstName" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Image" class="control-label"></label> <input type="file" name="Image" id="Image" multiple /> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" id="submit" /> </div> </form> </div> </div> @section scripts{ <script> $('#submit').click(function (e) { e.preventDefault(); var formData = new FormData(); var fileInput = $('#Image')[0].files[0]; formData.append("FirstName", $('#FirstName').val()); formData.append("Image", fileInput); $.ajax({ method: "post", url: '@Url.Action("Index")', data: formData, processData: false, contentType: false, success: function (response) { console.log(response); } }); }); </script> }
or
public class FileUploadVm { public string FirstName { get; set; } public IFormFile Image { get; set; } }
[HttpPost] public async Task<IActionResult> Index(FileUploadVm vm) { // full path to file in temp location var filePath = Path.GetTempFileName(); using (var stream = new FileStream(filePath, FileMode.Create)) { await vm.Image.CopyToAsync(stream); } return Ok(new { filePath, vm.FirstName }); }
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Thursday, April 25, 2019 3:55 PM -
User-921158202 posted
@mgebhard :
worked like a charm,
thanks a lot !
Thursday, April 25, 2019 4:32 PM