[英]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. 我想将请求从我的js文件发送到我的控制器中。
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. 我在这里面临的问题是我得到了$ scope.Employees的值,但fd为空。 This is a part of uploading file with some data in AngularJS
这是在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)
{ }
}}
Try this: 尝试这个:
$http({
method:"POST",
url:"Employees/",
transformRequest: angular.identity,
headers: { 'Content-Type': undefined },
data:{obj_emp1:$scope.Employee , obj_emp:fd }
}).then(
function success(data){
$scope.AddEditEmployee = false;
getEmployees();},
function error(data){
});
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"];
.........
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.