Uploading Multiple Files and form Object through an ASP.NET Web API Service using angular-material-fileinput (AngularJS)
HTML :
<md-content>
<md-tabs md-dynamic-height md-border-bottom>
<md-tab label="Basic Info">
<md-content class="md-padding">
<md-card>
<md-card-title>
<md-card-title-text>
<span class="md-headline">Basic Information Preferences</span>
<span class="md-subhead">Tell us a little about the venue.</span>
</md-card-title-text>
</md-card-title>
<md-card-content>
<div layout-gt-xs="row">
<md-input-container class="md-block" flex-gt-sm>
<label>Venue Name</label>
<input ng-model="formData.VENUE_NAME">
</md-input-container>
</div>
<div layout-gt-xs="row">
<md-input-container class="md-block" flex-gt-sm>
<label>Address</label>
<input ng-model="formData.VENUE_ADDRESS">
</md-input-container>
<md-input-container class="md-block" flex-gt-sm>
<label>Email</label>
<input ng-model="formData.VENUE_EMAIL">
</md-input-container>
</div>
<div layout-gt-sm="row">
<md-input-container class="md-block" flex-gt-sm>
<label>Region</label>
<md-select ng-model="formData.VENUE_REGION" placeholder="Region">
<md-option ng-repeat="outlet in regions" ng-value="outlet.REGION_ID">
{{outlet.REGION_NAME}}
</md-option>
</md-select>
</md-input-container>
<md-input-container class="md-block" flex-gt-sm>
<label>District</label>
<md-select ng-model="formData.VENUE_DISTRICT" placeholder="District">
<md-option ng-repeat="district in districts" ng-value="district.SUB_DIVISION_ID">
{{district.SUB_DIVISION_NAME}}
</md-option>
</md-select>
</md-input-container>
<md-input-container class="md-block" flex-gt-sm>
<label>Zone</label>
<md-select ng-model="formData.VENUE_ZONE" placeholder="Zone">
<md-option ng-repeat="location in zones" ng-value="location.ZONE_ID">
{{location.ZONE_NAME}}
</md-option>
</md-select>
</md-input-container>
<md-input-container class="md-block" flex-gt-sm flex="50">
<label>Geo Area</label>
<md-select ng-model="formData.VENUE_GEO_AREA" placeholder="Geo Area">
<md-option ng-repeat="location in geoAreas" ng-value="location.GEO_AREA_ID">
{{location.GEO_AREA_NAME}}
</md-option>
</md-select>
</md-input-container>
</div>
<div layout-gt-sm="row">
<md-input-container class="md-block" flex-gt-sm>
<label>Contact 1</label>
<input ng-model="formData.VENUE_CONTACT_1">
</md-input-container>
</div>
<div layout-gt-sm="row">
<md-input-container class="md-block" flex-gt-sm>
<label>Contact 2</label>
<input ng-model="formData.VENUE_CONTACT_2">
</md-input-container>
</div>
<div layout-gt-sm="row">
<md-input-container class="md-block" flex-gt-sm>
<label>Description</label>
<input ng-model="formData.VENUE_DESCRIPTION">
</md-input-container>
</div>
<div layout-gt-xs="row">
<md-input-container class="md-block" flex-gt-sm>
<label>Bank</label>
<input ng-model="formData.VENUE_BANK">
</md-input-container>
<md-input-container class="md-block" flex-gt-sm>
<label>Payment Terms With HX</label>
<input ng-model="formData.VENUE_PAYMENT_TERMS_WITH_HX">
</md-input-container>
</div>
<div layout-gt-xs="row">
<md-input-container class="md-block" flex-gt-sm>
<label>Payment System </label>
<input ng-model="formData.VENUE_PAYMENT_SYSTEM">
</md-input-container>
<md-input-container class="md-block" flex-gt-sm>
<label>Venue Special Offers</label>
<input ng-model="formData.VENUE_SPECIAL_OFFERS">
</md-input-container>
<md-input-container class="md-block" flex-gt-sm>
<label>Venue Outlet</label>
<input ng-model="formData.VENUE_OUTLET">
</md-input-container>
</div>
<div layout-gt-sm="row">
<md-checkbox ng-model="formData.IS_SEPARATE_MEETING_ROOM">
<label>DOES VENUE HAS SEPARATE MEETING ROOM</label>
</md-checkbox>
</div>
<div layout-gt-sm="row">
<md-checkbox ng-model="formData.IS_AGREEMENT">
<label>AGREEMENT</label>
</md-checkbox>
</div>
<div layout-gt-sm="row">
<md-checkbox ng-model="formData.IS_MEETING_ROOM">
<label>MEETING ROOM</label>
</md-checkbox>
</div>
<div layout-gt-sm="row">
<md-checkbox ng-model="formData.IS_FOOD_DELIVERY_OPTION_AVAILABLE">
<label>FOOD DELIVERY OPTION AVAILABLE</label>
</md-checkbox>
</div>
<div flex="100">
<h2 class="md-title">Rate Chart</h2>
<md-divider></md-divider>
</div>
<div layout-gt-sm="row" style="margin-top: 15px;">
<md-checkbox ng-model="formData.IS_RATE_CHART">
<label>IS RATE CHART FILE AVAILABLE</label>
</md-checkbox>
</div>
<div layout-gt-sm="row">
<lf-ng-md-file-input style="width: 100%" ng-disabled="!formData.IS_RATE_CHART" lf-maxcount="4" lf-files="RATE_CHART_FILE" lf-placeholder="Pick Image for Rate Chart" lf-remove-label="Delete" drag preview></lf-ng-md-file-input>
</div>
<div flex="100">
<h2 class="md-title">Venue Amenity & Feature</h2>
<md-divider></md-divider>
</div>
<div class="row" style="margin-top: 15px; height: 300px; overflow: auto">
<div class="col-lg-4 col-sm-4 col-md-6" ng-repeat="service in services track by $index">
<md-checkbox ng-checked="existsServices(service.AMENITY_ID, SelectedServices)"
ng-click="toggleServices(service.AMENITY_ID, SelectedServices)">
<label>{{service.AMENITY_NAME}}</label>
</md-checkbox>
</div>
</div>
<div flex="100">
<h2 class="md-title">Select Food Items for Venue</h2>
<md-divider></md-divider>
</div>
<div class="row" style="margin-top: 15px;">
<div class="col-lg-4 col-sm-4 col-md-6" ng-repeat="menu in foodMenus track by $index">
<md-checkbox ng-checked="exists(menu.FOOD_MENU_ID, FoodMenuSelected)"
ng-click="toggle(menu.FOOD_MENU_ID, FoodMenuSelected)">
<label>{{menu.FOOD_MENU_NAME}}</label>
</md-checkbox>
</div>
</div>
</md-card-content>
</md-card>
</md-content>
</md-tab>
<md-tab label="Photo">
<md-content class="md-padding">
<lf-ng-md-file-input lf-maxcount="4" lf-files="files08" lf-option="optoin08" lf-placeholder="Pick Image" lf-browse-label="Search" lf-remove-label="Delete" multiple drag preview ng-disabled="disabled06"></lf-ng-md-file-input>
</md-content>
</md-tab>
<md-tab label="Hall">
<md-content class="md-padding">
<md-card-content>
<form ng-submit="addNew()">
<div class="row" style="padding-top: 10px">
<div id="no-more-tables">
<table class="col-md-12 table-bordered table-striped table-condensed cf text-center">
<thead class="text-center">
<tr>
<th style="border: 1px solid white; border-bottom: 1px solid #ddd;">
</th>
<th style="border: 1px solid white; border-bottom: 1px solid #ddd;"> </th>
<th style="border: 1px solid white; border-bottom: 1px solid #ddd;"> </th>
<th style="border: 1px solid white; border-bottom: 1px solid #ddd;"> </th>
<th style="border: 1px solid white; border-bottom: 1px solid #ddd; border-right: 1px solid #ddd; "> </th>
<th style="text-align: center;">
<img src="{{AuthService.authentication.url}}/img/Banquet.png" />
</th>
<th style="text-align: center">
<img src="{{AuthService.authentication.url}}/img/Theater.png" />
</th>
<th style="text-align: center">
<img src="{{AuthService.authentication.url}}/img/Conference.png" />
</th>
<th style="text-align: center">
<img src="{{AuthService.authentication.url}}/img/Reception.png" />
</th>
<th style="text-align: center">
<img src="{{AuthService.authentication.url}}/img/Class.png" />
</th>
<th style="text-align: center">
<img src="{{AuthService.authentication.url}}/img/U-shape.png" />
</th>
<th style="text-align: center">
<img src="{{AuthService.authentication.url}}/img/Hallow-square.png" />
</th>
<th style="text-align: center">
<img src="{{AuthService.authentication.url}}/img/Dinner-dance.png" />
</th>
</tr>
<tr>
<th><input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" /></th>
<th>Name</th>
<th>Room Size(Feet)</th>
<th>Room Area(FT<sup>2</sup>)</th>
<th>Ceiling Height</th>
<th>Banquet</th>
<th>Theater</th>
<th>Conference</th>
<th>Reception</th>
<th>Class</th>
<th>U-Shape</th>
<th>Hollow Square</th>
<th>Dinner Dance</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="hall in halls">
<td data-title="checkbox">
<input type="checkbox" ng-model="hall.selected" />
</td>
<td data-title="NAME">
<input type="text" class="form-control" ng-model="hall.HALL_NAME" required />
</td>
<td data-title="ROOM_SIZE">
<input type="text" class="form-control" ng-model="hall.ROOM_SIZE" required />
</td>
<td data-title="ROOM_AREA">
<input type="text" class="form-control" ng-model="hall.ROOM_AREA" />
</td>
<td data-title="CEILING_HEIGHT">
<input type="text" class="form-control" ng-model="hall.CEILING_HEIGHT" />
</td>
<td data-title="BANQUET">
<input type="text" class="form-control" ng-model="hall.BANQUET" />
</td>
<td data-title="THEATER">
<input type="text" class="form-control" ng-model="hall.THEATER" />
</td>
<td data-title="CONFERENCE">
<input type="text" class="form-control" ng-model="hall.CONFERENCE" />
</td>
<td data-title="RECEPTION">
<input type="text" class="form-control" ng-model="hall.RECEPTION" />
</td>
<td data-title="CLASS">
<input type="text" class="form-control" ng-model="hall.CLASS" />
</td>
<td data-title="U_SHAPE">
<input type="text" class="form-control" ng-model="hall.U_SHAPE" />
</td>
<td data-title="HOLLOW_SQUARE">
<input type="text" class="form-control" ng-model="hall.HOLLOW_SQUARE" />
</td>
<td data-title="DINNER_SPACE">
<input type="text" class="form-control" ng-model="hall.DINNER_SPACE" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row" style="padding-top: 10px">
<input ng-hide="!halls.length" type="button" class="btn btn-danger pull-left" ng-click="remove()" value="Remove">
<input type="submit" class="btn btn-primary addnew pull-left" value="Add New">
</div>
</form>
</md-card-content>
</md-content>
</md-tab>
</md-tabs>
<md-content class="md-padding">
<md-card>
<md-card-content>
<div layout="row" layout-align="center center" style="text-align: center">
<md-button class="md-raised md-primary" ng-click="Clear()"><i class="fa fa-remove" aria-hidden="true"></i> Clear </md-button>
<md-button ng-disable="isLoading" class="md-raised md-primary" ng-click="Create()">
<i class="fa fa-save" aria-hidden="true" ng-if="!isLoading"></i>
<span ng-show="ButtonText == 'Loading'"><i class="glyphicon glyphicon-refresh spinning"></i></span>
{{ ButtonText }}
</md-button>
</div>
<div class="row">
<md-content class="md-padding">
<div class="input-field col s10 m10 l10" style="text-align: center">
<server-side-message message='serverMessage'></server-side-message>
</div>
</md-content>
</div>
</md-card-content>
</md-card>
</md-content>
</md-content>
Angular js Controller :
app.controller('VenueNewController', [
'$scope', '$resource', '$routeParams', '$location', 'HttpRequestService', 'AuthService', '$http', 'localStorageService', 'ActionMessageService', '$mdDialog', 'ApiEndPoints', function ($scope, $resource, $routeParams, $location, HttpRequestService, AuthService, $http, localStorageService, ActionMessageService, $mdDialog, ApiEndPoints) {
$scope.formData = {};
$scope.ButtonText = "Create";
$scope.isLoading = false;
$scope.AuthService = AuthService;
$scope.RedirectedToList = function () {
$location.path('/venue');
};
$scope.Clear = function () {
$scope.formData = {};
$scope.files08 = [];
$scope.serverMessage = "";
};
$scope.LoadDistrict = function () {
HttpRequestService.get("api/AddressSubDivision/get/1/20000/all").then(function (response) {
$scope.districts = response.data.items;
}, function (response) {
console.log("error");
$scope.serverMessage = ActionMessageService.getErrorMessage(response);
console.log(response);
});
};
$scope.LoadFoodMenu = function () {
HttpRequestService.get("api/FoodMenu/get/1/20000/all").then(function (response) {
$scope.foodMenus = response.data.items;
}, function (response) {
console.log("error");
$scope.serverMessage = ActionMessageService.getErrorMessage(response);
console.log(response);
});
};
$scope.LoadAmenities = function () {
HttpRequestService.get("api/Amenity/get/1/20000/all").then(function (response) {
$scope.services = response.data.items;
}, function (response) {
console.log("error");
$scope.serverMessage = ActionMessageService.getErrorMessage(response);
console.log(response);
});
};
$scope.halls = [];
$scope.addNew = function (hall) {
$scope.halls.push({
'HALL_NAME': "",
'ROOM_SIZE': "",
'ROOM_AREA': "",
'CEILING_HEIGHT': "",
'BANQUET': "",
'THEATER': "",
'CONFERENCE': "",
'RECEPTION': "",
'CLASS': "",
'U_SHAPE': "",
'HOLLOW_SQUARE': "",
'DINNER_SPACE': ""
});
};
$scope.remove = function () {
var newDataList = [];
$scope.selectedAll = false;
angular.forEach($scope.halls, function (selected) {
if (!selected.selected) {
newDataList.push(selected);
}
});
$scope.halls = newDataList;
};
$scope.checkAll = function () {
if (!$scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.halls, function (personalDetail) {
personalDetail.selected = $scope.selectedAll;
});
};
$scope.FoodMenuSelected = [];
$scope.toggle = function (item, list) {
var idx = list.indexOf(item);
if (idx > -1) list.splice(idx, 1);
else list.push(item);
};
$scope.exists = function (item, list) {
return list.indexOf(item) > -1;
};
$scope.SelectedServices = [];
$scope.toggleServices = function (item, list) {
var idx = list.indexOf(item);
if (idx > -1) list.splice(idx, 1);
else list.push(item);
};
$scope.existsServices = function (item, list) {
return list.indexOf(item) > -1;
};
$scope.LoadZone = function () {
HttpRequestService.get("api/Zone/get/1/20000/all").then(function (response) {
$scope.zones = response.data.items;
}, function (response) {
console.log("error");
$scope.serverMessage = ActionMessageService.getErrorMessage(response);
console.log(response);
});
};
$scope.LoadRegion = function () {
HttpRequestService.get("api/Region/get/1/20000/all").then(function (response) {
$scope.regions = response.data.items;
}, function (response) {
console.log("error");
$scope.serverMessage = ActionMessageService.getErrorMessage(response);
console.log(response);
});
}
$scope.LoadGeoArea = function () {
HttpRequestService.get("api/GeoArea/get/1/20000/all").then(function (response) {
$scope.geoAreas = response.data.items;
}, function (response) {
console.log("error");
$scope.serverMessage = ActionMessageService.getErrorMessage(response);
console.log(response);
});
}
$scope.Create = function () {
var invalidHall = false;
angular.forEach($scope.halls, function (value) {
console.log(value);
if (value.HALL_NAME == "") {
invalidHall = true;
}
});
if (invalidHall) {
alert("Invalid hall");
return;
}
$scope.isLoading = true;
$scope.ButtonText = "Loading";
var fd = new FormData();
var FoodMenuList = [];
angular.forEach($scope.FoodMenuSelected, function (value, key) {
var obj = {};
obj.FOOD_MENU_ID = value;
FoodMenuList.push(obj);
});
$scope.formData.FoodMenuList = FoodMenuList;
var SelectedServiceList = [];
angular.forEach($scope.SelectedServices, function (value, key) {
var obj = {};
obj.AMENITY_ID = value;
SelectedServiceList.push(obj);
});
$scope.formData.AmenityList = SelectedServiceList;
$scope.formData.HallList = $scope.halls;
fd.append('venue', JSON.stringify($scope.formData));
fd.append('file1', $scope.files08[0] ? $scope.files08[0].lfFile: "");
fd.append('file2', $scope.files08[1] ? $scope.files08[1].lfFile: "");
fd.append('file3', $scope.files08[2] ? $scope.files08[2].lfFile : "");
fd.append('file4', $scope.files08[3] ? $scope.files08[3].lfFile : "");
fd.append('RATE_CHART_FILE', $scope.RATE_CHART_FILE[0] ? $scope.RATE_CHART_FILE[0].lfFile : "");
console.log($scope.files08);
$http.post(AuthService.authentication.url+'/api/venue/create', fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined,
}
})
.success(function (response) {
$scope.serverMessage = ActionMessageService.getSuccessMessage(response);
$scope.ButtonText = "Create";
$scope.isLoading = false;
})
.error(function (response) {
$scope.serverMessage = ActionMessageService.getFileUploadExceptionMessage(response);
$scope.ButtonText = "Create";
$scope.isLoading = false;
});
};
$scope.LoadDistrict();
$scope.LoadZone();
$scope.LoadRegion();
$scope.LoadGeoArea();
$scope.LoadFoodMenu();
$scope.LoadAmenities();
}]);
Web API C#:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
[Authorize]
[HttpPost]
[Route("api/venue/create")]
public async Task<HttpResponseMessage> Post()
{
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new HttpResponseException
(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
List<VENUE_IMAGES> venueImagess = new List<VENUE_IMAGES>();
var uploadPath = HttpContext.Current.Server.MapPath("~/Uploads");
var multipartFormDataStreamProvider = new MultipartFormDataStreamProvider(uploadPath);
var result = await Request.Content.ReadAsMultipartAsync(multipartFormDataStreamProvider);
var model = result.FormData["venue"];
VENUE venueObj = JsonConvert.DeserializeObject<VENUE>(model);
if (venueObj == null)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
#region validation check
var context = new ValidationContext(venueObj, serviceProvider: null, items: null);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(venueObj, context, validationResults, true);
ValidationContext vc = new ValidationContext(venueObj);
foreach (var error in validationResults)
{
ModelState.AddModelError("", error.ErrorMessage);
}
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
#endregion
venueObj.VENUE_ID = Guid.NewGuid();
venueObj.ENTRY_BY = User.Identity.Name;
venueObj.ENTRY_DATE = DateTime.Now;
venueObj.UPDATE_DATE = DateTime.Now;
#region chagne guid file name to main file name with venueID
foreach (MultipartFileData fileData in multipartFormDataStreamProvider.FileData)
{
string fileName = "";
if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
{
fileName = Guid.NewGuid().ToString();
}
fileName = fileData.Headers.ContentDisposition.FileName;
if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
{
fileName = fileName.Trim('"');
}
if (fileName.Contains(@"/") || fileName.Contains(@"\"))
{
fileName = Path.GetFileName(fileName);
}
long IMAGE_SIZE = new FileInfo(fileData.LocalFileName).Length;
if (File.Exists(Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads/"), venueObj.VENUE_ID + "_" + fileName)))
{
File.Delete(Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads/"), venueObj.VENUE_ID + "_" + fileName));
}
File.Move(fileData.LocalFileName,
Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads/"), venueObj.VENUE_ID + "_" + fileName));
if (fileData.Headers.ContentDisposition.Name == "\"RATE_CHART_FILE\"")
{
venueObj.RATE_CHART_URL = "/Uploads/" + venueObj.VENUE_ID + "_" + fileName;
}
else
{
venueImagess.Add(new VENUE_IMAGES { VENUE_ID = venueObj.VENUE_ID, IMAGE_NAME = venueObj.VENUE_ID + "_" + fileName, IMAGE_URL = "/Uploads/" + venueObj.VENUE_ID + "_" + fileName, ENTRY_BY = User.Identity.Name, ENTRY_DATE = DateTime.Now, IMAGE_SIZE = IMAGE_SIZE, UPDATE_DATE = DateTime.Now });
}
}
#endregion
if (!service.ValidateVenue(venueObj))
{
VenueViewModel venueViewModel = new VenueViewModel();
venueViewModel.Venue = venueObj;
venueViewModel.VenueImages = venueImagess;
service.Save(venueViewModel);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Duplicate Venue");
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
Comments
Post a Comment