Answered by:
File Upload by ajax with multiple values

Question
-
User1888635512 posted
File Upload by ajax with multiple values. The values are passed to the controller function but the file value is not passed.
Jqueryfunction addemployee() { var name = $('#txtname').val(); var address = $('#txtaddress').val(); var gender = $('input[name=txtgender2]:checked').val(); var phone = $('#txtphone').val(); var homephone = $('#txthomephone').val(); var email = $('#txtemail').val(); var dob = $('#txtdob').val(); var city = $('#txtcity').val(); var state = $('#txtstate').val(); var country = $('#txtcountry').val(); var aadharno = $('#txtaadhar').val(); var pancardno = $('#txtpancard').val(); var experience = $('#txtexperience').val(); var bankname = $('#txtbankname').val(); var accountno = $('#txtaccountnumber').val(); var ifsccode = $('#txtifsc').val(); var branch = $('#txtbranch').val(); var joindate = $('#txtjoindate').val(); var department = $('#txtdepartment').val(); var designation = $('#txtdesignation').val(); var file = $('#proimage').val(); var image = JSON.stringify(file); var formData = new FormData(); var totalFiles = document.getElementById("proimage").files.length; for (var i = 0; i < totalFiles; i++) { var file = document.getElementById("proimage").files[i]; formData.append("proimage", file); } $.ajax({ type: "Post", contentType: "application/json;charset=utf-8", url: "/Common/addemployee", dataType: "json", data: "{'name':'" + name + "','address':'" + address + "','gender':'" + gender + "','phone':'" + phone + "','homephone':'" + homephone + "','email':'" + email + "','dob':'" + dob + "','city':'" + city + "','state':'" + state + "','country':'" + country + "','aadharno':'" + aadharno + "','pancardno':'" + pancardno + "','experience':'" + experience + "','bankname':'" + bankname + "','accountno':'" + accountno + "','ifsccode':'" + ifsccode + "','branch':'" + branch + "','joindate':'" + joindate + "','department':'" + department + "','designation':'" + designation + "','file':'" + formData + "'}", formData, success: function (response) { if (response == "Success") { setTimeout(function () { swal({ title: "Success!", text: "Employee Details Successfully Added!", type: "success", confirmButtonText: "OK" }, function (isConfirm) { if (isConfirm) { $('#btnaddemp').prop('disabled', false); window.location.href = "/Common/Employee"; } }); }, 1000); } else if (response == "Phone") { setTimeout(function () { swal({ title: "Duplication!", text: "Employee Phone Already Exist!", type: "warning", confirmButtonText: "OK" }, function (isConfirm) { if (isConfirm) { $('#btnaddemp').prop('disabled', false); //window.location.href = "/Common/Employee"; } }); }, 1000); } else if (response == "Email") { setTimeout(function () { swal({ title: "Duplication!", text: "Employee Email Already Exist!", type: "warning", confirmButtonText: "OK" }, function (isConfirm) { if (isConfirm) { $('#btnaddemp').prop('disabled', false); //window.location.href = "/Common/Employee"; } }); }, 1000); } }, error: function (response) { setTimeout(function () { swal({ title: "Error!", text: "Some issues found out in adding employee details!", type: "warning", confirmButtonText: "OK" }, function (isConfirm) { if (isConfirm) { window.location.href = "/Common/Employee"; } }); }, 1000); } }); }
Controller
[HttpPost] public ActionResult addemployee(string name,string address,string gender,string phone,string homephone,string email,string dob,string city,string state,string country,string aadharno,string pancardno,string experience,string bankname,string accountno,string ifsccode,string branch,string joindate,string department,string designation, HttpPostedFileBase file) { var model = addemp( name, address, gender, phone, homephone, email, dob, city, state, country, aadharno, pancardno, experience, bankname, accountno, ifsccode, branch, joindate, department, designation, file); return Json(model, JsonRequestBehavior.AllowGet); } [WebMethod] public string addemp(string name, string address, string gender, string phone, string homephone, string email, string dob, string city, string state, string country, string aadharno, string pancardno, string experience, string bankname, string accountno, string ifsccode, string branch, string joindate, string department, string designation, HttpPostedFileBase file) { MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnStringDb1"].ConnectionString); var phonecheck = "Select * From tbl_employ Where Phone = '" + phone + "'"; MySqlDataAdapter sda = new MySqlDataAdapter(phonecheck, con); DataTable dt = new DataTable(); sda.Fill(dt); if (dt.Rows.Count == 0) { var emailcheck = "Select * from tbl_employ Where Email = '" + email + "'"; MySqlDataAdapter ee = new MySqlDataAdapter(emailcheck, con); DataTable dee = new DataTable(); ee.Fill(dee); if (dee.Rows.Count == 0) { var totalleaves = 0; var totaloffs = 0; var status = "Active"; var empmax = "Select Max(Index_Id) as Id From tbl_employ"; MySqlDataAdapter empmaxda = new MySqlDataAdapter(empmax, con); DataTable empmaxdt = new DataTable(); empmaxda.Fill(empmaxdt); var value = empmaxdt.Rows[0]["Id"].ToString(); if (value != "") { if (file != null && file.ContentLength > 0) { int id = Convert.ToInt32(value); id = id + 1; var fileName = ("EMP-00" + id + "-img" + System.IO.Path.GetExtension(file.FileName)); if (fileName != "") { var filePath = Path.Combine(Server.MapPath("~/Pictures/Employee/"), fileName); if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } file.SaveAs(filePath); var Empcode = "Emp-00" + id; var add = "Insert Into tbl_employ (`Emp_Code`,`Name`,`Address`,`Gender`,`Phone`,`Home_Phone`,`Email`,`Date_of_Birth`,`City`,`State`,`Country`,`Aadhar_Number`,`Pancard_Number`,`Experience`,`Bank_Name`,`Bank_Account_Number`,`Bank_IFSC_Code`,`Bank_Branch`,`Date_of_Join`,`Department`,`Designation`,`Total_Leaves`,`Total_Offs`,`Status`) VALUES ('" + Empcode + "','" + name + "','" + address + "','" + gender + "','" + phone + "','" + homephone + "','" + email + "','" + dob + "','" + city + "','" + state + "','" + country + "','" + aadharno + "','" + pancardno + "','" + experience + "','" + bankname + "','" + accountno + "','" + ifsccode + "','" + branch + "','" + joindate + "','" + department + "','" + designation + "','" + totalleaves + "','" + totaloffs + "','" + status + "')"; MySqlCommand addemploy = new MySqlCommand(add, con); con.Open(); addemploy.ExecuteNonQuery(); return "Success"; } } return ""; } else { if (file != null && file.ContentLength > 0) { var fileName = ("EMP-001-img" + System.IO.Path.GetExtension(file.FileName)); if (fileName != "") { var filePath = Path.Combine(Server.MapPath("~/Pictures/Employee/"), fileName); if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } file.SaveAs(filePath); var Empcode = "Emp-001"; var add = "Insert Into tbl_employ (`Emp_Code`,`Name`,`Address`,`Gender`,`Phone`,`Home_Phone`,`Email`,`Date_of_Birth`,`City`,`State`,`Country`,`Aadhar_Number`,`Pancard_Number`,`Experience`,`Bank_Name`,`Bank_Account_Number`,`Bank_IFSC_Code`,`Bank_Branch`,`Date_of_Join`,`Department`,`Designation`,`Total_Leaves`,`Total_Offs`,`Status`) VALUES ('" + Empcode + "','" + name + "','" + address + "','" + gender + "','" + phone + "','" + homephone + "','" + email + "','" + dob + "','" + city + "','" + state + "','" + country + "','" + aadharno + "','" + pancardno + "','" + experience + "','" + bankname + "','" + accountno + "','" + ifsccode + "','" + branch + "','" + joindate + "','" + department + "','" + designation + "','" + totalleaves + "','" + totaloffs + "','" + status + "')"; MySqlCommand addemploy = new MySqlCommand(add, con); con.Open(); addemploy.ExecuteNonQuery(); return "Success"; } } return ""; } } else { return "Email"; } } else { return "Phone"; } }
Image file Id = proimage...
Friday, November 16, 2018 10:51 AM
Answers
-
User-271186128 posted
Hi Michael.Samuel,
File Upload by ajax with multiple values. The values are passed to the controller function but the file value is not passed.Have you solved your problem? If not, please refer to the following code, it works well on my side:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $('#btnUpload').click(function () { // Checking whether FormData is available in browser if (window.FormData !== undefined) { var fileUpload = $("#FileUpload1").get(0); var files = fileUpload.files; // Create FormData object var fileData = new FormData(); // Looping over all files and add it to FormData object for (var i = 0; i < files.length; i++) { fileData.append(files[i].name, files[i]); } // Adding one more key to FormData object fileData.append('username', "Manas"); $.ajax({ url: '/Home/UploadFiles', type: "POST", contentType: false, // Not to set any content header processData: false, // Not to process data data: fileData, success: function (result) { alert(result); }, error: function (err) { alert(err.statusText); } }); } else { alert("FormData is not supported."); } }); }); </script>
Code in the controller method:
[HttpGet] public ActionResult UploadFiles() { return View(); } [HttpPost] public ActionResult UploadFiles(string username) { // Checking no of files injected in Request object if (Request.Files.Count > 0) { try { // Get all files from Request object HttpFileCollectionBase files = Request.Files; for (int i = 0; i < files.Count; i++) { //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/"; //string filename = Path.GetFileName(Request.Files[i].FileName); HttpPostedFileBase file = files[i]; string fname; // Checking for Internet Explorer if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER") { string[] testfiles = file.FileName.Split(new char[] { '\\' }); fname = testfiles[testfiles.Length - 1]; } else { fname = file.FileName; } // Get the complete folder path and store the file inside it. fname = Path.Combine(Server.MapPath("~/Uploads/"), fname); file.SaveAs(fname); } // Returns message that successfully uploaded return Json("File Uploaded Successfully!"); } catch (Exception ex) { return Json("Error occurred. Error details: " + ex.Message); } } else { return Json("No files selected."); } }
Code from this article.
Best regards,
Dillion- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, November 21, 2018 9:55 AM
All replies
-
User475983607 posted
FormData is used to send multipart/form-data and not stringified application/json.
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
Friday, November 16, 2018 3:56 PM -
User503812343 posted
for using FormData.... Model binding needs to be used.
It does not look models has used.
Friday, November 16, 2018 6:48 PM -
User-271186128 posted
Hi Michael.Samuel,
File Upload by ajax with multiple values. The values are passed to the controller function but the file value is not passed.Have you solved your problem? If not, please refer to the following code, it works well on my side:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $('#btnUpload').click(function () { // Checking whether FormData is available in browser if (window.FormData !== undefined) { var fileUpload = $("#FileUpload1").get(0); var files = fileUpload.files; // Create FormData object var fileData = new FormData(); // Looping over all files and add it to FormData object for (var i = 0; i < files.length; i++) { fileData.append(files[i].name, files[i]); } // Adding one more key to FormData object fileData.append('username', "Manas"); $.ajax({ url: '/Home/UploadFiles', type: "POST", contentType: false, // Not to set any content header processData: false, // Not to process data data: fileData, success: function (result) { alert(result); }, error: function (err) { alert(err.statusText); } }); } else { alert("FormData is not supported."); } }); }); </script>
Code in the controller method:
[HttpGet] public ActionResult UploadFiles() { return View(); } [HttpPost] public ActionResult UploadFiles(string username) { // Checking no of files injected in Request object if (Request.Files.Count > 0) { try { // Get all files from Request object HttpFileCollectionBase files = Request.Files; for (int i = 0; i < files.Count; i++) { //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/"; //string filename = Path.GetFileName(Request.Files[i].FileName); HttpPostedFileBase file = files[i]; string fname; // Checking for Internet Explorer if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER") { string[] testfiles = file.FileName.Split(new char[] { '\\' }); fname = testfiles[testfiles.Length - 1]; } else { fname = file.FileName; } // Get the complete folder path and store the file inside it. fname = Path.Combine(Server.MapPath("~/Uploads/"), fname); file.SaveAs(fname); } // Returns message that successfully uploaded return Json("File Uploaded Successfully!"); } catch (Exception ex) { return Json("Error occurred. Error details: " + ex.Message); } } else { return Json("No files selected."); } }
Code from this article.
Best regards,
Dillion- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, November 21, 2018 9:55 AM -
User1888635512 posted
Thanks for all the supports. Thank you
Thursday, November 22, 2018 6:01 AM