Akhilesh Sehgal Akhilesh Sehgal - 4 months ago 13
AngularJS Question

Send two objects with $http.post in AngularJS while uploading a file with some data

I want to send a request from my js file to my controller in angular.

What I am doing is

var fd = new FormData();
for (var i = 0; i < file.length; i++) {
fd.append("file", file[i]);
}

$http.post('Employees/', $scope.Employee, fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).success(function (data) {
$scope.AddEditEmployee = false;
getEmployees();
}).error(function (data, status, headers, config) {
});


The problem i face here is that I get the values of $scope.Employees but the fd comes empty. This is a part of uploading file with some data in AngularJS

Code in my controller is

public class EmployeesController: ApiController
{
EmployeeDM objEmpManager = new EmployeeDM(BaseDapper.CreateInstance());
[Route("Employees/")]
[HttpPost]
public void Post(EmployeeBO obj_emp)
//public void Post(EmployeeBO obj_emp1, EmployeeBO obj_emp)
{
try
{
var httpRequest = HttpContext.Current.Request;
string image_names = string.Empty;
string ResumeName = string.Empty;
string resumePath = HttpContext.Current.Server.MapPath("/Uploads/Resume/");
if (httpRequest.Files.Count > 0)
{
string resume_full_path = string.Empty;
for (int i = 0; i < httpRequest.Files.Count; i++)
{
var postedFile = httpRequest.Files[i];
ResumeName = postedFile.FileName;
resume_full_path = resumePath + obj_emp.name + ResumeName;
postedFile.SaveAs(resume_full_path);
image_names += resume_full_path.ToString() + ',';
obj_emp.resume = resume_full_path;
if (obj_emp.employee_id > 0)
{
objEmpManager.UpdateEmployee(obj_emp);
}
else
{
objEmpManager.SaveEmployee(obj_emp);
}
}
}

}
catch (Exception ex)
{ }

}}

Answer

Try this.

var fd = new FormData();
for (var i = 0; i < file.length; i++) {
    fd.append("file", file[i]);
}

for (var key in $scope.Employee) {
        fd.append(key, $scope.Employee[key]);
        alert($scope.Employee[key]);
    }

$http.post('Employees/', fd, {
        headers: { 'Content-Type': undefined }
    }).success(function (data) {
        $scope.AddEditEmployee = false;
        getEmployees();
    }).error(function (data, status, headers, config) {
    });

From backend you need to remove object as parameter and find that from form of request.

    public void Post(){ 
EmployeeBo obj = new EmployeeBo();
obj.key= HttpContext.Current.Request.Form["Key"];

.........
 }