Reputation: 317
I'm trying to upload an image along with other types of data using web api, angular JS . My POST employee API controller action is :
[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);
}
The Service JavaScript is:
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;
};
});
The "AddEmployee " Controller which I'm using for posting employee to the server is
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;
});
};
});
The "Image" attribute Is not being posted to the server . rather it's throwing null. Probably problem with binding . I'm not sure why the image attribute is not being bind to the model while other attributes can.
Upvotes: 0
Views: 546
Reputation: 5176
I would assume that you are using an input with a type of file in your html to get the file name. Angular does not handle the binding for these automatically, so even though the file you selected shows up in the browser, it doesn't update the model. There are a number of directives available to work around this shortcoming.
This answer covers it pretty thoroughly. ng-model for <input type="file"/>
Upvotes: 1