您的位置:首页 > Web前端 > AngularJS

AngularJs增删改查例子

2018-04-01 18:24 375 查看
1、JS
app.controller("sysUserCtrl", function($scope, $modal, $filter, $http, $window, datadService, localization, toaster, Upload, $timeout) {

// 后端服务IP地址和端口
var serverIpPort = $window.localStorage["serverIpPort"]; 
// 获取令牌
var token = $window.localStorage["token"]; 

$scope.sysUser = {
userId : 1,
username : 'admin',
password : 'admin',
agencyId : 1
};

$scope.$on("controller.addData", function(event, e) {

var formData = e.formData;
$http({
      url : serverIpPort + '/sysUser',
      method : 'POST',
      headers : {
'X-Auth-Token' : token
},
  data : formData
    }).success(function(data) {
// var sysUserRole = {
// sysUser : {"userId":data},
// sysRole : {"roleId":formData.sysRole.roleId}
// };
//
// $http.post(serverIpPort + '/sysUserRole', sysUserRole);
}).then(function successCallback(response) {
formData.userId = data;
$scope.list.push(formData);
// 新增成功提示信息
toaster.pop('success', 
localization.localization("prompt.information"), 
localization.localization("prompt.addSuccess"));
        }, function errorCallback(response) {
        // 新增失败提示信息
        toaster.pop('error', 
localization.localization("prompt.information"), 
localization.localization("prompt.addFail"));
        });
});

$scope.$on("controller.editData", function(event, e) {

var formData = e.formData;
formData.userId = $scope.list[e.index].userId;
$scope.list[e.index] = formData;
$http({
      url : serverIpPort + '/sysUser',
      method : 'PUT',
      headers : {
'X-Auth-Token' : token
},
  data : formData
    }).then(function successCallback(response) {
// 修改成功提示信息
toaster.pop('success', 
localization.localization("prompt.information"), 
localization.localization("prompt.updateSuccess"));
}, function errorCallback(response) {
// 修改失败提示信息
toaster.pop('error', 
localization.localization("prompt.information"), 
localization.localization("prompt.updateFail"));
});
// var sysUserRole = {
// sysUserRoleId : {},
// sysUser : {"userId":data},
// sysRole : {"roleId":formData.sysRole.roleId}
// };
//
//
// $http.put(serverIpPort + '/sysUserRole', sysUserRole);
});

$scope.signingAgencyes = [];

$http({
url : serverIpPort + '/sysSigningAgency',
method : 'GET',
headers : {
'X-Auth-Token' : token
}
    }).then(function(data) {
   
angular.forEach(data.data, function(result){
$scope.signingAgencyes.push({
value : result.agencyId,
text : result.userName
});
});
    }, function(x) {
    $scope.authError = 'Server Error';
    });

$scope.showSigningAgency = function(signingAgency) {
var selected = [];
if (signingAgency && signingAgency.agencyId) {
selected = $filter('filter')(
$scope.signingAgencyes, {
value : signingAgency.agencyId
});
}
return selected.length ? selected[0].text
: '';
};

$scope.showSysRole = function(sysRole) {

var selected = [];
if (sysRole && sysRole.roleId) {
selected = $filter('filter')(
$scope.sysRoles, {
value : sysRole.roleId
});
}
return selected.length ? selected[0].text
: '';
};

$scope.showUserState = function(userState) {

if (userState==1) {
return localization.localization("com.effective");
} else {
return localization.localization("com.invalid");
}
};

$scope.sysRoles = [];

    $http({
      url : serverIpPort + '/sysRole',
      method : 'GET',
      headers : {
'X-Auth-Token' : token
}
    }).then(function(data) {

angular.forEach(data.data, function(result){
$scope.sysRoles.push({
value : result.roleId,
text : result.roleDesc
});
});
}, function(x) {
        $scope.authError = 'Server Error';
      });

$scope.selectPages = [ {
value : 10,
text : '10'
}, {
value : 20,
text : '20'
}, {
value : 30,
text : '30'
} ];

// 
$scope.pageNum = 0;
<
1d810
span style="white-space:pre;"> $scope.pageSize = 10;
// $scope.size = 0;
// $scope.orderBy = null;
// $scope.startRow = 0;
// $scope.endRow = 0;
$scope.total = 0;
$scope.pages = 0;
// $scope.list = [];
$scope.firstPage = 0;
$scope.prePage = 0;
$scope.nextPage = 0;
$scope.lastPage = 0;
// $scope.isFirstPage = false;
// $scope.isLastPage = true;
// $scope.hasPreviousPage = false;
// $scope.hasNextPage = false;
// $scope.navigatePages = 8;
// $scope.navigatepageNums = [];

// $scope.currentPage = 0;

// 首页
$scope.first = function() {
$scope.loading = true;
$scope.getPagedDataAsync($scope.firstPage, $scope.pageSize, $scope.filterOptions.filterText);
}

// 上一页
$scope.previous = function() {
$scope.loading = true;
$scope.getPagedDataAsync($scope.prePage, $scope.pageSize, $scope.filterOptions.filterText);
}

// 下一页
$scope.next = function() {
$scope.loading = true;
$scope.getPagedDataAsync($scope.nextPage, $scope.pageSize, $scope.filterOptions.filterText);
}

// 末页
$scope.last = function() {
$scope.loading = true;
$scope.getPagedDataAsync($scope.lastPage, $scope.pageSize, $scope.filterOptions.filterText);
}

// 更改每页条数
$scope.onChange = function() {
$scope.loading = true;
$scope.getPagedDataAsync($scope.pageNum, $scope.pageSize, $scope.filterOptions.filterText);
}

$scope.list = [];

// 搜索
$scope.filterOptions = {
filterText: document.getElementById("filter").value,
useExternalFilter: true
};

// 封装分页数据
$scope.setPagingData = function(data, page, pageSize){  

        angular.forEach(data.list, function(result){
$scope.list.push({
userId : result.userId,
username : result.username,
realname : result.realname,
phone : result.phone,
email : result.email,
weixin : result.weixin,
isSelected:false
});
});
        
        $scope.pageNum = data.pageNum;
    $scope.pageSize = data.pageSize;
    $scope.size = data.size;
    $scope.orderBy = data.orderBy;
    $scope.startRow = data.startRow;
    $scope.endRow = data.endRow;
    $scope.total = data.total;
    $scope.pages = data.pages;
   
    $scope.list = data.list;
    $scope.firstPage = data.firstPage;
    $scope.prePage = data.prePage;
    $scope.nextPage = data.nextPage;
    $scope.lastPage = data.lastPage;
    $scope.isFirstPage = data.isFirstPage;
    $scope.isLastPage = data.isLastPage;
    $scope.hasPreviousPage = data.hasPreviousPage;
    $scope.hasNextPage = data.hasNextPage;
    $scope.navigatePages = data.navigatePages;
    $scope.navigatepageNums = data.navigatepageNums;
        if (!$scope.$$phase) {
            $scope.$apply();
        }
    };
    
// 获取分页数据
    $scope.getPagedDataAsync = function (page, pageSize, searchText) {
   
        setTimeout(function () {
            var data;
            
            if (searchText == '') {
            searchText = 'undefined';
            }
       
            $http({
              url : serverIpPort + '/sysUserPageable/'+page+'/'+pageSize+'/'+searchText,
              method : 'GET',
              headers : {
    'X-Auth-Token' : token
    }
            }).then(function(largeLoad) {
            $scope.setPagingData(largeLoad.data,page,pageSize);
            $scope.loading = false;
        }, function(x) {
            $scope.authError = 'Server Error';
            $scope.loading = false;
        });
       
        }, 100);
    };
    
    $scope.loading = true;
    // 获取分页数据
    $scope.getPagedDataAsync($scope.pageNum, $scope.pageSize);
    
    // 搜索方法
    $scope.search=function(){
    $scope.filterOptions = {
        filterText: document.getElementById("filter").value,
        useExternalFilter: true
    }; 
    $scope.loading = true;
    $scope.getPagedDataAsync($scope.pageNum, $scope.pageSize, $scope.filterOptions.filterText);
    }
    
    $scope.checkStatus = function(){  
   
        var str = '';  
        angular.forEach($scope.list,function(value,key){  
          if(value.isSelected){  
            str += value.username+"被删除了\n";  
          }  
        });  
        if(str === ''){  
          str = '没有选中记录';  
        }  
        alert(str);  
      };  
      
      $scope.changeAll = function(){// 全选/取消全选
        angular.forEach($scope.list,function(v,k){  
          v.isSelected = $scope.selectAll;  
        })  
      };  
      
      $scope.funcChange = function(){// 当所有都选中时
        $scope.select = true;  
        angular.forEach($scope.list,function(v,k){  
          $scope.select = $scope.select && v.isSelected;  
        });  
      };    
    
    $scope.items = ['item1', 'item2', 'item3'];
$scope.del = function(index) {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
        controller: 'ModalInstanceCtrl',
        resolve: {
        items: function () {
        return $scope.items;
        }
        }
});
modalInstance.result.then(function (selectedItem) {
$http({
url : serverIpPort + '/sysUser/'+$scope.list[index].userId,
method : 'DELETE',
headers : {
'X-Auth-Token' : token
}
}).then(function successCallback(response) {
$scope.list.splice(index, 1);
// 删除成功提示信息
toaster.pop('success', 
localization.localization("prompt.information"), 
localization.localization("prompt.delSuccess"));
        }, function errorCallback(response) {
        // 删除失败提示信息
        toaster.pop('error', 
localization.localization("prompt.information"), 
localization.localization("prompt.delFail"));
        });
}, function () {});
}

$scope.add = function() {
$scope.$broadcast("controller.add");
}

$scope.edit = function(index) {
$scope.$broadcast("controller.edit", {
formData : $scope.list[index],
index : index
});
}

$scope.see = function(index) {

$scope.$broadcast("controller.see", {
formData : $scope.list[index],
index : index
});
}

// form
var EDIT_MODE = 1;
var ADD_MODE = -1;
$scope.isShowList = true;
$scope.isShowForm = false;
$scope.isShowDetail = false;

$scope.$on("controller.add", function(event, data) {
$scope.isShowList = false;
$scope.isShowForm = true;
$scope.mode = ADD_MODE;
// 用户状态默认为有效  
$scope.formData.userState = 1;
$scope.data = {
file : null
    };
});

$scope.$on("controller.edit", function(event, e) {
$scope.isShowList = false;
$scope.isShowForm = true;
$scope.formData.username = e.formData.username;
$scope.formData.password = e.formData.password;
$scope.formData.confirm_password = e.formData.password;
$scope.formData.realname = e.formData.realname;
$scope.formData.phone = e.formData.phone;
$scope.formData.email = e.formData.email;
$scope.formData.userState = e.formData.userState;
$scope.formData.userImage = e.formData.userImage;
$scope.formData.qq = e.formData.qq;
$scope.formData.weixin = e.formData.weixin;
$scope.formData.blog = e.formData.blog;
$scope.formData.personalProfile = e.formData.personalProfile;
$scope.formData.latitudeLongitude = e.formData.latitudeLongitude;
$scope.formData.sysSigningAgency = e.formData.sysSigningAgency;
$scope.formData.sysRole = e.formData.sysRole;
$scope.formData.remark = e.formData.remark;
$scope.mode = e.index;
// 下载用户头像
$scope.fileUploadVo = {
id : e.formData.userId,
fileName : e.formData.userImageName,
filePath : e.formData.userImagePath
};
$http({
url : serverIpPort + '/sysUser/download',
data : $scope.fileUploadVo,
    method : 'POST',
    headers : {
'X-Auth-Token' : token
},
responseType: 'blob'
    }).then(function successCallback(response) {
    debugger
    var blob = new Blob([response.data], {type: "application/octet-stream;charset=utf-8"});    
    var file_ = new File([blob], "image.jpg", {type:"image/jpg"});
    $scope.data = {
    file : file_
    };
        }, function errorCallback(response) {
        // 下载失败提示信息
        toaster.pop('error', 
localization.localization("prompt.information"), 
localization.localization("prompt.downloadFail"));
        });
});

$scope.$on("controller.see", function(event, e) {
$scope.isShowList = false;
$scope.isShowForm = false;
$scope.isShowDetail = true;
$scope.formData.username = e.formData.username;
$scope.formData.password = e.formData.password;
$scope.formData.confirm_password = e.formData.confirm_password;
$scope.formData.realname = e.formData.realname;
$scope.formData.phone = e.formData.phone;
$scope.formData.email = e.formData.email;
$scope.formData.userState = e.formData.userState;
$scope.formData.userImage = e.formData.userImage;
$scope.formData.qq = e.formData.qq;
$scope.formData.weixin = e.formData.weixin;
$scope.formData.blog = e.formData.blog;
$scope.formData.personalProfile = e.formData.personalProfile;
$scope.formData.latitudeLongitude = e.formData.latitudeLongitude;
$scope.formData.sysSigningAgency = e.formData.sysSigningAgency;
$scope.formData.sysRole = e.formData.sysRole;
$scope.formData.remark = e.formData.remark;
$scope.mode = e.index;
// 下载用户头像
$scope.fileUploadVo = {
id : e.formData.userId,
fileName : e.formData.userImageName,
filePath : e.formData.userImagePath
};
$http({
url : serverIpPort + '/sysUser/download',
data : $scope.fileUploadVo,
    method : 'POST',
    headers : {
'X-Auth-Token' : token
},
responseType: 'blob'
    }).then(function successCallback(response) {
    debugger
    var blob = new Blob([response.data], {type: "application/octet-stream;charset=utf-8"});    
    var img = document.getElementById("userImage2");
    img.onload = function(e) {
    window.URL.revokeObjectURL(img.src); // 清除释放
    };
    img.src = window.URL.createObjectURL(blob);
        }, function errorCallback(response) {
        // 下载失败提示信息
        toaster.pop('error', 
localization.localization("prompt.information"), 
localization.localization("prompt.downloadFail"));
        });
});

$scope.formData = {
username : "",
password : "",
confirm_password : "",
realname : "",
phone : ""
};

$scope.submit = function(invalid) {
if(invalid) {
// 校验不通过
        toaster.pop('error', 
localization.localization("prompt.information"), 
localization.localization("prompt.invalid"));
        return;
}
var data = {
formData : {
userId : $scope.formData.userId,
username : $scope.formData.username,
password : $scope.formData.password,
realname : $scope.formData.realname,
phone : $scope.formData.phone,
email : $scope.formData.email,
userState : $scope.formData.userState,
userImage : $scope.formData.userImage,
qq : $scope.formData.qq,
weixin : $scope.formData.weixin,
blog : $scope.formData.blog,
personalProfile : $scope.formData.personalProfile,
latitudeLongitude : $scope.formData.latitudeLongitude,
sysSigningAgency : $scope.formData.sysSigningAgency,
sysRole : $scope.formData.sysRole,
remark : $scope.formData.remark
}
};
// 如果已经上传了用户头像,则将相关信息保存到表单中。
debugger
if($scope.data.file!=null && $scope.result!=null) {
data.formData.userImageName = $scope.data.file.name;
data.formData.userImagePath = $scope.result.filePath;
}
if ($scope.mode != ADD_MODE) {
data.index = $scope.mode;
$scope.$emit("controller.editData", data);
} else {
$scope.$emit("controller.addData", data);
}

$scope.clean();
$scope.isShowList = true;
$scope.isShowForm = false;
}

$scope.close = function(immediate) {
if (!immediate) {
var modalInstance = $modal.open({
templateUrl: 'updateModal.html',
        controller: 'ModalInstanceCtrl',
        resolve: {
        items: function () {
        return $scope.items;
        }
        }
});
modalInstance.result.then(function (selectedItem) {
$scope.clean();
$scope.isShowList = true;
$scope.isShowForm = false;
});
}
}

$scope.back = function() {
$scope.clean();
$scope.isShowList = true;
$scope.isShowForm = false;
$scope.isShowDetail = false;
}

$scope.clean = function() {
$scope.formData.username = "";
$scope.formData.password = "";
$scope.formData.confirm_password = "";
$scope.formData.realname = "";
$scope.formData.phone = "";
$scope.formData.email = "";
$scope.formData.userState = "";
$scope.formData.userImage = "";
$scope.formData.qq = "";
$scope.formData.weixin = "";
$scope.formData.blog = "";
$scope.formData.personalProfile = "";
$scope.formData.latitudeLongitude = "";
$scope.formData.sysSigningAgency = "";
$scope.formData.sysRole = "";
$scope.formData.remark = "";
}

// 文件上传

$scope.data = {
file : null
};

// 上传
$scope.upload = function() {
debugger
if (!$scope.data.file) {
return;
}
Upload.upload({
url : serverIpPort + '/upload',
data : $scope.data,
headers : {
'X-Auth-Token' : token
}
}).then(
function(response) {
$timeout(function() {
$scope.result = response.data;
// 上传成功提示信息
toaster.pop('success', 
localization.localization("prompt.information"), 
localization.localization("prompt.uploadSuccess"));
});
},
function(response) {

if (response.status > 0) {
$scope.errorMsg = response.status + ': '
+ response.data;
// 上传失败提示信息
        toaster.pop('error', 
localization.localization("prompt.information"), 
localization.localization("prompt.uploadFail"));
}
},
function(evt) {
$scope.progress = parseInt(100.0 * evt.loaded
/ evt.total);
});
};

// 下载
$scope.download = function(formData) {
$scope.fileUploadVo = {
fileName : formData.attaContent,
filePath : formData.attaPath
};
$http({
url : serverIpPort + '/download',
data : $scope.fileUploadVo,
    method : 'POST',
    headers : {
'X-Auth-Token' : token
},
responseType: 'blob'
    }).then(function successCallback(response) {
    // 下载成功提示信息
toaster.pop('success', 
localization.localization("prompt.information"), 
localization.localization("prompt.downloadSuccess"));
    var blob = new Blob([response.data], {type: "application/octet-stream;charset=utf-8"});    
         var fileName = formData.attaContent;    
         var a = document.createElement("a");    
         document.body.appendChild(a);    
         a.download = fileName;    
         a.href = URL.createObjectURL(blob);    
         a.click();    
        }, function errorCallback(response) {
        // 下载失败提示信息
        toaster.pop('error', 
localization.localization("prompt.information"), 
localization.localization("prompt.downloadFail"));
        });
}

});

2、HTML
<div class="bg-light lter b-b wrapper-md">
<h1 class="m-n font-thin h3">
<span translate="system.sysUser.sysUser">sysUser</span>
</h1>
</div>
<div class="wrapper-md">
<!-- toaster directive -->
<toaster-container
toaster-options="{'position-class': 'toast-top-right', 'close-button':true}"></toaster-container>
<!-- / toaster directive -->
<div class="row wrapper" ng-show="isShowList">
<div class="col-sm-4 m-b-xs">
<div class="input-group">
<input id="filter" type="text" class="input-sm form-control">
<span class="input-group-btn">
<button class="btn btn-sm btn-default" type="button"
ng-click="search()">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</div>
<div class="col-sm-4 m-b-xs">
<div class="input-group">
<button class="input-sm form-control" ng-click="add()">
<i class="fa fa-plus"></i><span translate="com.add">add</span>
</button>
</div>
</div>
<div class="col-sm-4 m-b-xs"></div>
</div>
<div ng-show="isShowList">
<table class="table table-hover table-condensed bg-white-only">
<thead>
<tr class="ng-scope" style="font-weight: bold">
<td class="v-middle"
style="width: 15%; height: 47px; background: #F5F5F5; text-align: center;"><p
style="border-left: 1px solid #BBBBBB; margin: 0 0 0 36px;">
<span translate="system.sysUser.username"
style="margin-left: 10px;" />
</p></td>
<td class="v-middle"
style="width: 15%; background: #F5F5F5; text-align: center;"><p
style="border-left: 1px solid #BBBBBB; margin: 0 0 0 36px;">
<span translate="system.sysUser.realname"
style="margin-left: 10px;" />
</p></td>
<td class="v-middle"
style="width: 15%; background: #F5F5F5; text-align: center;"><p
style="border-left: 1px solid #BBBBBB; margin: 0 0 0 36px;">
<span translate="system.sysUser.phone" style="margin-left: 10px;" />
</p></td>
<td class="v-middle"
style="width: 35%; background: #F5F5F5; text-align: center;"><p
style="border-left: 1px solid #BBBBBB; margin: 0 0 0 36px;">
<span translate="system.sysSigningAgency"
style="margin-left: 10px;" />
</p></td>
<td class="v-middle"
style="width: 20%; background: #F5F5F5; text-align: center;"><p
style="border-left: 1px solid #BBBBBB; margin: 0 0 0 36px;">
<span translate="com.ops" style="margin-left: 10px;" />
</p></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in list">
<td class="v-middle">
<!-- editable roleDesc (text with validation) --> <span
editable-text="item.username" e-name="username" e-form="rowform"
e-required style="margin-left: 30px;"> {{ item.username ||
'' }} </span>
</td>
<td class="v-middle">
<!-- editable realname (text with validation) --> <span
editable-text="item.realname" e-name="realname" e-form="rowform"
e-required style="margin-left: 30px;"> {{ item.realname ||
'' }} </span>
</td>
<td class="v-middle">
<!-- editable phone (text with validation) -->
<p>
<span editable-text="item.phone" e-name="phone" e-form="rowform"
e-required style="margin-left: 30px;"> {{ item.phone ||
'' }} </span>
</td>
<td class="v-middle"><span editable-select="item.saUserName"
e-name="saUserName" e-form="rowform"
e-ng-options="i.value as i.text for i in signingAgencyes"
style="margin-left: 30px;"> {{
showSigningAgency(item.sysSigningAgency) }} </span></td>
<td style="white-space: nowrap; text-align: center;">
<!-- form -->
<div class="buttons" style="margin-left: 30px;">
<button class="btn btn-sm btn-info" ng-click="see($index)">
<i class="fa fa-search"></i><span translate="com.see" />
</button>
<button class="btn btn-sm btn-info" ng-click="edit($index)">
<i class="fa fa-edit"></i><span translate="com.edit" />
</button>
<script type="text/ng-template" id="myModalContent.html">
<div ng-include="'tpl/com/delModal.html'"></div>
</script>
<button class="btn btn-sm btn-danger" ng-click="del($index)">
<i class="fa fa-trash-o"></i><span translate="com.del" />
</button>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="6" class="text-center">
<div class="col-sm-4 m-b-xs">
<span translate="com.total" />:{{total}}
</div>
<div class="col-sm-4 m-b-xs">
<div class="input-group">
<span translate="com.page" /><select style="width: 50px"
ng-model="pageSize"
ng-options="i.value as i.text for i in selectPages"
ng-change="onChange()">
</select><span translate="com.strip" />
</div>
</div>
<div class="col-sm-4 m-b-xs">
<div class="input-group">
<button type="button" class="btn btn-default" ng-click="first()">
<i class="fa fa-angle-double-left"></i>
</button>
<button type="button" class="btn btn-default"
ng-click="previous()">
<i class="fa fa-angle-left"></i>
</button>
<input id="pageNum" type="text" class="input-sm"
style="width: 50px" value="{{pageNum}}">/{{pages}}
<button type="button" class="btn btn-default" ng-click="next()">
<i class="fa fa-angle-right"></i>
</button>
<button type="button" class="btn btn-default" ng-click="last()">
<i class="fa fa-angle-double-right"></i>
</button>
</div>
</div>
</td>
</tr>
</tfoot>
</table>
</div>
<div class="panel-body" ng-show="isShowForm">
<div class="row">
<form name="myForm" class="form-horizontal">
<div class="col-sm-9">
<div class="form-group">
<!-- 登录帐号 -->
<label class="col-sm-2 control-label" for="username"><span
translate="system.sysUser.username" /></label>
<div class="col-sm-4">
<input type="text" class="form-control" id="username"
name="username" ng-model="formData.username"
ng-pattern="/^[a-zA-Z0-9]{4,10}$/" required> <span
style="color: red"
ng-show="myForm.username.$dirty && myForm.username.$invalid">
<span ng-show="myForm.username.$invalid"><span
translate="vld.invalid" /><span translate="vld.username" /></span> </span>
</div>
<!-- 用户密码 -->
<label class="col-sm-2 control-label" for="password"><span
translate="system.sysUser.password" /></label>
<div class="col-sm-4">
<input type="password" id="password" name="password"
class="form-control" ng-model="formData.password"
ng-pattern="/^[a-zA-Z0-9]{6,20}$/" required> <span
style="color: red"
ng-show='myForm.password.$dirty && myForm.password.$invalid'><span
translate="vld.password"></span></span>
</div>
</div>
<div class="form-group">
<!-- 确认用户密码 -->
<label class="col-sm-2 control-label" for="confirm_password"><span
translate="com.confirm" /><span
translate="system.sysUser.password" /></label>
<div class="col-sm-4">
<input type="password" id="confirm_password"
name="confirm_password" class="form-control"
ng-model="formData.confirm_password"
ui-validate=" '$value==formData.password' "
ui-validate-watch=" 'formData.password' " required> <span
style="color: red"
ng-show='myForm.confirm_password.$dirty && myForm.confirm_password.$error.validator'><span
translate="vld.confirm_password" /></span>
</div>
<!-- 用户姓名 -->
<label class="col-sm-2 control-label" for="realname"><span
translate="system.sysUser.realname" /></label>
<div class="col-sm-4">
<input type="text" class="form-control" id="realname"
ng-model="formData.realname" ng-maxlength="100" required>
</div>
</div>
<div class="form-group">
<!-- 手机号 -->
<label class="col-sm-2 control-label" for="phone"><span
translate="system.sysUser.phone" /></label>
<div class="col-sm-4">
<input type="text" id="phone" name="phone" class="form-control"
ng-model="formData.phone" ng-pattern="/^1[0-9][0-9]\d{4,8}$/"
ng-required="true"> <span style="color: red"
ng-show='myForm.phone.$dirty && myForm.phone.$invalid'><span
translate="vld.phone" /></span>
</div>
<!-- 电子邮箱 -->
<label class="col-sm-2 control-label" for="email"><span
translate="system.sysUser.email" /></label>
<div class="col-sm-4">
<input type="email" id="email" name="email" class="form-control"
ng-model="formData.email" ng-maxlength="100" required> <span
style="color: red"
ng-show="myForm.email.$dirty && myForm.email.$invalid"> <span
ng-show="myForm.email.$error.email"><span
translate="vld.email" /></span> </span>
</div>
</div>
<div class="form-group">
<!-- QQ号 -->
<label class="col-sm-2 control-label" for="qq"><span
translate="system.sysUser.qq" /></label>
<div class="col-sm-4">
<input type="text" class="form-control" id="qq" name="qq"
ng-model="formData.qq" ng-maxlength="100"> <span
style="color: red"
ng-show='myForm.qq.$dirty && myForm.qq.$invalid'><span
translate="vld.MaxLength"></span></span>
</div>
<!-- 微信号 -->
<label class="col-sm-2 control-label" for="weixin"><span
translate="system.sysUser.weixin" /></label>
<div class="col-sm-4">
<input type="text" id="weixin" name="weixin" class="form-control"
ng-model="formData.weixin" ng-maxlength="100"> <span
style="color: red"
ng-show='myForm.weixin.$dirty && myForm.weixin.$invalid'><span
translate="vld.MaxLength"></span></span>
</div>
</div>
<div class="form-group">
<!-- 微博帐户 -->
<label class="col-sm-2 control-label" for="blog"><span
translate="system.sysUser.blog" /></label>
<div class="col-sm-4">
<input type="text" class="form-control" id="blog" name="blog"
ng-model="formData.blog" ng-maxlength="100"> <span
style="color: red"
ng-show='myForm.blog.$dirty && myForm.blog.$invalid'><span
translate="vld.MaxLength"></span></span>
</div>
<!-- 经纬度 -->
<label class="col-sm-2 control-label" for="latitudeLongitude"><span
translate="system.sysUser.latitudeLongitude" /></label>
<div class="col-sm-4">
<input type="text" class="form-control" id="latitudeLongitude"
name="latitudeLongitude" ng-model="formData.latitudeLongitude"
ng-maxlength="100"> <span style="color: red"
ng-show='myForm.latitudeLongitude.$dirty && myForm.latitudeLongitude.$invalid'><span
translate="vld.MaxLength"></span></span>
</div>
</div>
<div class="form-group">
<!-- 签约机构 -->
<label class="col-sm-2 control-label" for="sysSigningAgency"><span
translate="system.sysUser.sysSigningAgency" /></label>
<div class="col-sm-4">
<select class="form-control m-b" id="sysSigningAgency"
ng-model="formData.sysSigningAgency.agencyId"
ng-options="i.value as i.text for i in signingAgencyes" required>
<option value=""><span translate="com.select" /></option>
</select>
</div>
<!-- 用户角色 -->
<label class="col-sm-2 control-label" for="sysRole"><span
translate="system.sysUser.sysUserRole" /></label>
<div class="col-sm-4">
<select class="form-control m-b" id="sysRole"
ng-model="formData.sysRole.roleId"
ng-options="i.value as i.text for i in sysRoles" required>
<option value=""><span translate="com.select" /></option>
</select>
</div>
</div>
<div class="form-group">
<!-- 用户状态 -->
<label class="col-sm-2 control-label" for="userState"><span
translate="system.sysUser.userState" /></label>
<div class="col-sm-4">
<div class="radio">
<label class="i-checks"> <input type="radio" name="userState"
value="1" ng-model="formData.userState" checked>
<i></i>     <span translate="com.effective">effective</span>
</label> <label class="i-checks">        <input type="radio" name="userState"
value="0" ng-model="formData.userState"> <i></i>
    <span translate="com.invalid">invalid</span>
</label>
</div>
</div>
</div>
<div class="form-group">
<!-- 个人简介 -->
<label class="col-sm-2 control-label" for="personalProfile"><span
translate="system.sysUser.personalProfile" /></label>
<div class="col-sm-10">
<textarea id="personalProfile" name="personalProfile"
class="form-control" rows="6"
ng-model="formData.personalProfile" ng-maxlength="1000"></textarea>
<span style="color: red"
ng-show='myForm.name.$dirty && myForm.name.$invalid'><span
translate="vld.MaxLength"></span></span>
</div>
</div>
<div class="form-group">
<!-- 备注 -->
<label class="col-sm-2 control-label" for="remark"><span
translate="system.sysUser.remark" /></label>
<div class="col-sm-10">
<textarea id="remark" name="remark" class="form-control" rows="6"
ng-model="formData.remark" ng-maxlength="100"></textarea>
<span style="color: red"
ng-show='myForm.remark.$dirty && myForm.remark.$invalid'><span
translate="vld.MaxLength"></span></span>
</div>
</div>
</div>
<div class="col-sm-3" style="padding-top: 50px;">
<!-- 用户头像 -->
<div class="form-group">
<label class="col-sm-8 control-label" for="userImage"><span
translate="system.sysUser.userImage" /></label>
</div>
<div class="form-group" style="padding-left: 70px;">
<div style="width: 150px; height: 180px; background: #E4E4E4">
<img id="userImage" ngf-src="data.file" ngf-background="file"
style="background: #E4E4E4; overflow: hidden; width: 150px; height: 180px;"
ngf-resize="{width: 150, height: 180, quality: 0.9}"
ngf-no-object-url="true" />
</div>
<div class="form-group"
style="padding-left: 50px; padding-top: 10px;">
<div class="col-sm-8">
<button class="btn btn-sm btn-default" ngf-select="ngfSelect()"
ngf-pattern=image/* ngf-multiple="false" ng-model="data.file">
<span translate="com.browse" />...
</button>
<button class="btn btn-sm btn-default" ng-click="upload()"
ng-show="data.file">
<i class="fa fa-upload"></i><span translate="com.upload" />
</button>
</div>
</div>
</div>
</div>
<div class="col-sm-12" style="text-align: center;">
<div class="col-sm-4 col-sm-offset-4">
<button type="submit" class="btn btn-primary"
ng-disabled="form.$invalid">
<span translate="com.save" ng-click="submit(myForm.$invalid)">save</span>
</button>
<script type="text/ng-template" id="updateModal.html">
<div ng-include="'tpl/com/updateModal.html'"></div>
</script>
<button type="submit" class="btn btn-default">
<span translate="com.cancel" ng-click="close(false)">cancel</span>
</button>
</div>
</div>
</form>
</div>
</div>
<div ng-show="isShowDetail" class="dataFormController">
<div class="row">
<form role="form" name="form" class="form-horizontal">
<div class="col-sm-9">
<div class="form-group">
<!-- 登录帐号 -->
<label class="col-sm-2 control-label" for="username"><span
translate="system.sysUser.username" /></label>
<div class="col-sm-4">
<label class="control-label" id="username">{{formData.username}}</label>
</div>
<!-- 用户密码 -->
<label class="col-sm-2 control-label" for="password"><span
translate="system.sysUser.password" /></label>
<div class="col-sm-4">
<label class="control-label" id="password">******</label>
</div>
</div>
<div class="form-group">
<!-- 用户姓名 -->
<label class="col-sm-2 control-label" for="realname"><span
translate="system.sysUser.realname" /></label>
<div class="col-sm-4">
<label class="control-label" id="username">{{formData.realname}}</label>
</div>
<!-- 手机号 -->
<label class="col-sm-2 control-label" for="phone"><span
translate="system.sysUser.phone" /></label>
<div class="col-sm-4">
<label class="control-label" id="phone">{{formData.phone}}</label>
</div>
</div>
<div class="form-group">
<!-- 电子邮箱 -->
<label class="col-sm-2 control-label" for="email"><span
translate="system.sysUser.email" /></label>
<div class="col-sm-4">
<label class="control-label" id="email">{{formData.email}}</label>
</div>
<!-- QQ号 -->
<label class="col-sm-2 control-label" for="qq"><span
translate="system.sysUser.qq" /></label>
<div class="col-sm-4">
<label class="control-label" id="qq">{{formData.qq}}</label>
</div>
</div>
<div class="form-group">
<!-- 微信号 -->
<label class="col-sm-2 control-label" for="weixin"><span
translate="system.sysUser.weixin" /></label>
<div class="col-sm-4">
<label class="control-label" id="weixin">{{formData.weixin}}</label>
</div>
<!-- 微博帐户 -->
<label class="col-sm-2 control-label" for="blog"><span
translate="system.sysUser.blog" /></label>
<div class="col-sm-4">
<label class="control-label" id="blog">{{formData.blog}}</label>
</div>
</div>
<div class="form-group">
<!-- 经纬度 -->
<label class="col-sm-2 control-label" for="latitudeLongitude"><span
translate="system.sysUser.latitudeLongitude" /></label>
<div class="col-sm-4">
<label class="control-label" id="latitudeLongitude">{{formData.latitudeLongitude}}</label>
</div>
<!-- 签约机构 -->
<label class="col-sm-2 control-label" for="sysSigningAgency"><span
translate="system.sysUser.sysSigningAgency" /></label>
<div class="col-sm-4">
<label class="control-label" id="sysSigningAgency">{{formData.sysSigningAgency.agencyName}}</label>
</div>
</div>
<div class="form-group">
<!-- 用户角色 -->
<label class="col-sm-2 control-label" for="sysUserRole"><span
translate="system.sysUser.sysUserRole" /></label>
<div class="col-sm-4">
<label class="control-label" id="sysUserRole">{{showSysRole(formData.sysRole)}}</label>
</div>
<!-- 用户状态 -->
<label class="col-sm-2 control-label" for="userState"><span
translate="system.sysUser.userState" /></label>
<div class="col-sm-4">
<label class="control-label" id="userState">{{showUserState(formData.userState)}}</label>
</div>
</div>
<div class="form-group">
<!-- 个人简介 -->
<label class="col-sm-2 control-label" for="personalProfile"><span
translate="system.sysUser.personalProfile" /></label>
<div class="col-sm-10">
<label class="control-label" style="text-align: center;"
id="personalProfile">{{formData.personalProfile}}</label>
</div>
</div>
<div class="form-group">
<!-- 备注 -->
<label class="col-sm-2 control-label" for="remark"><span
translate="system.sysUser.remark" /></label>
<div class="col-sm-10">
<label class="control-label" style="text-align: center;"
id="remark">{{formData.remark}}</label>
</div>
</div>

</div>
<div class="col-sm-3" style="padding-top: 50px;">
<!-- 用户头像 -->
<div class="form-group">
<label class="col-sm-8 control-label" for="userImage"><span
translate="system.sysUser.userImage" /></label>
</div>
<div class="form-group" style="padding-left: 70px;">
<div style="width: 150px; height: 180px; background: #E4E4E4">
<img id="userImage2" ngf-src="formData.userImage"
ngf-background="file"
style="background: #E4E4E4; overflow: hidden; width: 150px; height: 180px;"
ngf-resize="{width: 150, height: 180, quality: 0.9}"
ngf-no-object-url="true" />
</div>
</div>
</div>
</form>
</div>
<div class="col-sm-12" style="text-align: center;">
<div class="col-sm-4 col-sm-offset-4">
<button type="submit" class="btn btn-default">
<span ng-click="back()" translate="com.back">back</span>
</button>
</div>
</div>
</div>
</div>
<div class="loadingcontainer" ng-show="loading">
<div ng-include="'tpl/com/loading.html'"></div>

</div>
3、Java
package com.daqiang.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.labwinner.common.ResultVo;
import com.labwinner.domain.SysUser;
import com.labwinner.service.SysUserService;
import com.labwinner.vo.FileUploadVo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

/**
 * @Description 用户Controller
 * @author daqiang
 * @version V1.0
 * @date 2017年5月18日
 * 
 * @Company Daqiang Studio
 * @Copyright Copyright (c) 2017, All rights reserved.
 */
@RestController
public class SysUserController {

private static Logger logger = LoggerFactory
.getLogger(SysUserController.class);

@Autowired
private SysUserService sysUserService;

@Value("${sysUserPhone.upload-path}")
String filePath;

@Value("${sysUserPhone.url-path}")
String urlPath;

/**
* 服务端文件上传路径
*/
@Value("${server.upload.path}")
String uploadPath;

/**
* @Description 获取所有对象
* @author daqiang
* @version V1.0
* @date 2017年5月18日
*/
@RequestMapping(value = "/sysUser", method = RequestMethod.GET)
@ResponseBody
public List<SysUser> getAll() {
return sysUserService.getAll();
}

/**
* @Description 获取所有对象
* @author daqiang
* @version V1.0
* @date 2017年5月18日
*/
@RequestMapping(value = "/sysUserGetProList", method = RequestMethod.GET)
@ResponseBody
public List<SysUser> getProList() {
return sysUserService.getProList();
}

/**
* @Description 获取所有对象
* @author daqiang
* @version V1.0
* @date 2017年5月18日
*/
@RequestMapping(value = "/sysUserGetProRoleAll", method = RequestMethod.GET)
@ResponseBody
public List<SysUser> getProRoleAll() {
return sysUserService.getProRoleAll();
}

/**
* @Description 根据查询条件获取对象
* @author daqiang
* @version V1.0
* @date 2017年5月18日
*/
@RequestMapping(value = "/sysUserPageable/{page}/{pageSize}/{filter}", method = RequestMethod.GET)
@ResponseBody
public PageInfo getAllPageable(@PathVariable Integer page,
@PathVariable Integer pageSize, @PathVariable String filter) {
if (page != null && pageSize != null) {
PageHelper.startPage(page, pageSize);
}
List<SysUser> list = new ArrayList<SysUser>();
if (filter != null && filter != "" && !"undefined".equals(filter)) {
list = sysUserService.getAllPageable(filter);
} else {
list = sysUserService.getAll();
}
return new PageInfo(list);
}

@RequestMapping(value = "/sysUser/{id}", method = RequestMethod.GET)
public SysUser getById(@PathVariable("id") Long id) {
return sysUserService.getById(id);
}

@RequestMapping(value = "/sysUser", method = RequestMethod.POST)
public Integer save(@RequestBody SysUser sysUser) {
if(sysUser.getUserImagePath()!=null) {
byte[] buffer = null;
try {
File file = new File(uploadPath, sysUser.getUserImagePath());
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
sysUser.setUserImage(buffer);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return sysUserService.save(sysUser);
}

@RequestMapping(value = "/sysUser", method = RequestMethod.PUT)
public ResultVo update(@RequestBody SysUser sysUser) {
ResultVo resultVo = new ResultVo();
try {
if(sysUser.getUserImagePath()!=null) {
byte[] buffer = null;
try {
File file = new File(uploadPath, sysUser.getUserImagePath());
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
sysUser.setUserImage(buffer);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
sysUserService.update(sysUser);
resultVo.setErrCode(0);
resultVo.setErrMsg("update successe");
return resultVo;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
resultVo.setErrCode(1);
resultVo.setErrMsg("update fail");
return resultVo;
}
}

@RequestMapping(value = "/sysUser/{id}", method = RequestMethod.DELETE)
public void delete(@PathVariable("id") Long id) {
sysUserService.delete(id);
}

/**
* @param 下载用户头像
* @param response
* @param fileUploadVo
* @return
*/
@RequestMapping(value = "/sysUser/download", method = RequestMethod.POST)
public String downloadFile(
org.apache.catalina.servlet4preview.http.HttpServletRequest request,
HttpServletResponse response, @RequestBody FileUploadVo fileUploadVo) {
SysUser sysUser = sysUserService.getById(fileUploadVo.getId());
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;fileName="
+ sysUser.getUserImageName());
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
String fileName = UUID.randomUUID() + ".jpg";
try {
File file = byte2File(sysUser.getUserImage(), uploadPath, fileName);
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
logger.info("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}

/**
* @param byte 转文件
* @param filePath
* @param fileName
* @return
*/
public static File byte2File(byte[] buf, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {
dir.mkdirs();
}
file = new File(filePath + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(buf);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: