我尝试使用web api,angular JS上传图像和其他类型的数据。 我的POST员工API控制器操作是:
[ResponseType(typeof(Employee))]
public async Task<IHttpActionResult> PostEmployee(Employee employee)
{
byte[] data = new byte[employee.Image.ContentLength];
employee.Image.InputStream.Read(data, 0, employee.Image.ContentLength);
employee.Picture = data;
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Employees.Add(employee);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = employee.ID }, employee);
}
服务JavaScript是:
app.service('Service', function ($http) {
this.getEmployees = function () {
return $http.ger("/api/EmployeeApi");
}
this.post = function (Employee) {
var request = $http({
method: "post",
url: "/api/EmployeeApi/PostEmployee",
data: Employee,
headers: {
'Content-Type' : 'application/json'
}
});
return request;
};
});
&#34; AddEmployee&#34;我用来将员工发布到服务器的控制器是
app.controller('AddEmployee', function ($scope, Service) {
$scope.ID = 1;
$scope.save = function () {
var Employee = {
ID: $scope.ID,
Name: $scope.Name,
Experience: $scope.Experience,
EmployerName: $scope.EmployerName,
Image:$scope.Image
};
var Post = Service.post(Employee);
Post.then(function (pl) {
alert("Student Saved Successfully.");
},
function (errorPl) {
$scope.error = 'failure loading Student', errorPl;
});
};
});
&#34;图像&#34;属性未发布到服务器。相反,它扔了null。可能是绑定问题。我不确定为什么image属性没有绑定到模型,而其他属性可以。
答案 0 :(得分:1)
我会假设您在html中使用带有某种文件的输入来获取文件名。 Angular不会自动处理这些绑定,因此即使您选择的文件显示在浏览器中,它也不会更新模型。有许多指令可以解决这个缺点。
这个答案非常彻底。 ng-model for <input type="file"/>