【发布时间】:2016-09-29 17:04:49
【问题描述】:
我正在尝试使用 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;
};
});
我用于将员工发布到服务器的“AddEmployee”控制器是
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;
});
};
});
“图像”属性未发布到服务器。而是抛出空值。可能是绑定问题。我不确定为什么图像属性没有绑定到模型,而其他属性可以。
【问题讨论】:
-
你能调试你的 .NET 代码吗?我猜你的 Employee 没有正确绑定。尝试添加 [FromBody] 属性。而且最好在开头检查ModelState.IsValid
-
如果您尝试在
Employee对象中发送原始字节数组,那就是您的问题。但在继续之前,您必须调试NullReferenceException。 -
@CodeCaster ,这不是您提到的问题的重复。图片未发布到服务器,它正在抛出 null 。
-
@RomanKoliada ,我尝试调试。 “图像”抛出空值。这就是我出错的原因。
标签: angularjs asp.net-web-api image-uploading