I have currently started on AngularJs, my requirement is to post the Files to MVC controller via AngularJs. Below is the code snippet.
In my View I have
<input name="myFile" id="myFile" multiple type="file" ng-model="myFile"
upload-files/>
And this is my model,
public class EmployeeDto
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Department")]
public Nullable<int> DeptId { get; set; }
public List<int> PrivilegeId { get; set; }
public Department Department { get; set; }
public ICollection<EmployeePrivileges> EmployeePrivileges { get; set;}
public DateTime DateOfJoining { get; set; }
public byte[] EmpPhoto { get; set; }
public HttpPostedFileBase[] File { get; set; }
public bool IsActive { get; set; }
}
You can see the property HttpPostedFileBase[] File. I want to assign Uploaded files to this property through JSON, is it possible?
In my Controller.js
var app = angular.module("EmpApp", []);
//Directive for Upload Files
app.directive('uploadFiles', function () {
return {
scope: true, //create a new scope
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var files = event.target.files;
//iterate files since 'multiple' may be specified on the element
for (var i = 0; i < files.length; i++) {
//emit event upward
scope.$emit("selectedFile", { file: files[i] });
}
});
}
};
});
app.controller("EmpCtlr", function ($scope, EmpService) {
$scope.AddEmployee = function () {
// $scope.files = [];
if ($scope.Action == "Save") {
var employee = {
Id: $scope.Id,
Name: $scope.EmpName,
DateOfJoining: $scope.DOJ,
DeptId: $scope.selectedDept,
PrivilegeId: $scope.selectedPriv,
IsActive: 1
};
var addEmployee = EmpService.AddEmployeeSvc(employee);
addEmployee.then(function (msg) {
GetEmployees();
}, function () {
alert('Error in getting book records');
});
}
};
});
My Service.js.
this.AddEmployeeSvc = function (employee) {
return $http({
method: 'POST',
params:employee,
url: "Employee/AddEmployee",
headers: { 'Content-Type': undefined },
transformRequest: function () {
var formData = new FormData();
formData.append("myFile", Files);
return formData;
},
})
};
My MVC Controller Method
[HttpPost]
public void AddEmployee(EmployeeDto employee)
{
//I will have to say Request.Form for all input elements but how to
// get in employee object
//var _data = Request.Form["properties"];
//This is working
var photo =HttpContext.Request.Files.Count
}