Currently, I'm facing a challenge in uploading multiple files alongside regular form data. While I had successfully implemented this functionality in PHP before, I am now attempting to achieve the same in ASP.NET MVC4 using C#. Below is the HTML form I have:
<form action="/controller/actionane" name="applicationform" class="upload-form" method="post" onsubmit="return false;" enctype="multipart/form-data" id="userform">
<input class="form-control" type="file" class="upload-file" data-max-size="12582912" multiple="multiple" name="attachment[]" value="documents">
<input class="btn btn-success" type="submit" name="submit" onclick="formSubmit()" />
</form>
Included below is my JavaScript code utilizing jquery-1.11.1:
function formSubmit() {
var form = $("form[name='applicationform']");
var data = new FormData(form[0]);
$.ajax(
{
method: "POST",
url: form.attr("action"),
processData: false, // Don't process the files
contentType: false, cache: false, async: false,
data: data,
success: function (data) {
alert(data);
}
});
}
Here's a glimpse of how my controller is structured:
[HttpPost]
public JsonResult submitApplication(HttpPostedFileBase[] attachment)
{
string fil= "";
foreach (HttpPostedFileBase file in attachment)
{
/*Geting the file name*/
string filename = System.IO.Path.GetFileName(file.FileName);
fil += filename;
/*Saving the file in server folder*/
file.SaveAs(Server.MapPath("~/Images/" + filename));
string filepathtosave = "Images/" + filename;
/*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL IN DATA BASE*/
}
return this.Json(fil,JsonRequestBehavior.AllowGet);
}
Unfortunately, I'm encountering an issue where the files are not being passed to the parameter, resulting in an Object reference null exception. What steps should I take to rectify this and ensure everything runs smoothly?