I need to upload a file from my file input through ajax with multiple parameters through an ASP.NET MVC controller and I am getting an error. Save file from input to variable data2.
var data2 = new FormData();
var files;
var loadFile = function (event) {
files = $("#upload").get(0).files;
if (files.length > 0) {
data2.append("MyImages", files[0]);
}
};
Send data with ajax
$.ajax({
url: "/Adot/UploadAdopt",
type: "POST",
data: { ForUpload:data2,
Title:"New name"},
success: function (response) {
console.log(response);
}
});
Controller
[HttpPost]
public JsonResult UploadAdopt(HttpPostedFileBase ForUpload, string Title)
{
string path = Path.Combine(Server.MapPath("~/image/adopts"), Path.GetFileName(ForUpload.FileName));
ForUpload.SaveAs(path);
return Json("", JsonRequestBehavior.AllowGet);
}
multipart/form-data. TheFormDatainterface provides an easy way to construct this type of request. developer.mozilla.org/en-US/docs/Web/API/FormData