AngularJs增删改查例子

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;
$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



sysUser





toaster-options="{'position-class': 'toast-top-right', 'close-button':true}">










































style="width: 15%; height: 47px; background: #F5F5F5; text-align: center;"> style="border-left: 1px solid #BBBBBB; margin: 0 0 0 36px;">
style="margin-left: 10px;" />

style="width: 15%; background: #F5F5F5; text-align: center;"> style="border-left: 1px solid #BBBBBB; margin: 0 0 0 36px;">
style="margin-left: 10px;" />

style="width: 15%; background: #F5F5F5; text-align: center;"> style="border-left: 1px solid #BBBBBB; margin: 0 0 0 36px;">

style="width: 35%; background: #F5F5F5; text-align: center;"> style="border-left: 1px solid #BBBBBB; margin: 0 0 0 36px;">
style="margin-left: 10px;" />

style="width: 20%; background: #F5F5F5; text-align: center;"> style="border-left: 1px solid #BBBBBB; margin: 0 0 0 36px;">


editable-text="item.username" e-name="username" e-form="rowform"
e-required style="margin-left: 30px;"> {{ item.username ||
'' }}

editable-text="item.realname" e-name="realname" e-form="rowform"
e-required style="margin-left: 30px;"> {{ item.realname ||
'' }}



e-required style="margin-left: 30px;"> {{ item.phone ||
'' }}

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) }}










:{{total}}










style="width: 50px" value="{{pageNum}}">/{{pages}}














name="username" ng-model="formData.username"
ng-pattern="/^[a-zA-Z0-9]{4,10}$/" required> style="color: red"
ng-show="myForm.username.$dirty && myForm.username.$invalid">
translate="vld.invalid" />




class="form-control" ng-model="formData.password"
ng-pattern="/^[a-zA-Z0-9]{6,20}$/" required> style="color: red"
ng-show='myForm.password.$dirty && myForm.password.$invalid'> translate="vld.password">






name="confirm_password" class="form-control"
ng-model="formData.confirm_password"
ui-validate=" '$value==formData.password' "
ui-validate-watch=" 'formData.password' " required> style="color: red"
ng-show='myForm.confirm_password.$dirty && myForm.confirm_password.$error.validator'> translate="vld.confirm_password" />




ng-model="formData.realname" ng-maxlength="100" required>






ng-model="formData.phone" ng-pattern="/^1[0-9][0-9]\d{4,8}$/"
ng-required="true"> ng-show='myForm.phone.$dirty && myForm.phone.$invalid'> translate="vld.phone" />




ng-model="formData.email" ng-maxlength="100" required> style="color: red"
ng-show="myForm.email.$dirty && myForm.email.$invalid"> ng-show="myForm.email.$error.email"> translate="vld.email" />






ng-model="formData.qq" ng-maxlength="100"> style="color: red"
ng-show='myForm.qq.$dirty && myForm.qq.$invalid'> translate="vld.MaxLength">




ng-model="formData.weixin" ng-maxlength="100"> style="color: red"
ng-show='myForm.weixin.$dirty && myForm.weixin.$invalid'> translate="vld.MaxLength">






ng-model="formData.blog" ng-maxlength="100"> style="color: red"
ng-show='myForm.blog.$dirty && myForm.blog.$invalid'> translate="vld.MaxLength">




name="latitudeLongitude" ng-model="formData.latitudeLongitude"
ng-maxlength="100"> ng-show='myForm.latitudeLongitude.$dirty && myForm.latitudeLongitude.$invalid'> translate="vld.MaxLength">




























ng-show='myForm.name.$dirty && myForm.name.$invalid'> translate="vld.MaxLength">







ng-show='myForm.remark.$dirty && myForm.remark.$invalid'> translate="vld.MaxLength">










style="background: #E4E4E4; overflow: hidden; width: 150px; height: 180px;"
ngf-resize="{width: 150, height: 180, quality: 0.9}"
ngf-no-object-url="true" />

style="padding-left: 50px; padding-top: 10px;">





















































































































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" />














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 getAll() {
return sysUserService.getAll();
}


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

/**
* @Description 获取所有对象
* @author daqiang
* @version V1.0
* @date 2017年5月18日
*/
@RequestMapping(value = "/sysUserGetProRoleAll", method = RequestMethod.GET)
@ResponseBody
public List 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 list = new ArrayList();
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;
}


}

你可能感兴趣的:(AngularJS)