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

Spring Boot+AngularJS+BootStrap实现进度条示例代码

2017-03-02 15:31 1236 查看

Spring Boot+AngularJS+BootStrap实现进度条

原理

进度条的原理是在上传文件的时候,当程序运行到某一个部分,往Session中设置一个1到100的值。然后前台再每隔很小的一段时间去请求这个值。

在AngularJS中,$http对象有3种状态,分别是success,progress,error,其中progress方法就会在success方法调用之前(也就是上传完成之前),不断地调用。而我们要做的就是在progress中在添加一个请求,去后台拿我们设置在session中的值。

代码,这里我用了一个插件用来上传文件,叫ng-file-upload

html

<input type="file" data-ng-model="file">
<uib-progress data-ng-show="progress">
<uib-bar value="progress" type="{{type}}" data-ng-bind="progress + '%'"/>
</uib-progress>
<span class="err" data-ng-show="isShowMsg" data-ng-bind="Msg"></span>
<button class="btn btn-primary" type="button" data-ng-click="upload()">确认</button>

js

Upload.upload(
{
url: "",
data: {
file: file
},
method: 'post'
}).then(function (res) {
//这里是success方法
$scope.isShowMsg = true;
$scope.Msg = res.data.msg;
if($scope.Msg == "导入数据不符合格式要求!")
$scope.type = "progress-bar progress-bar-danger progress-bar-striped";//设置进度条样式
else {
$scope.type = "progress-bar progress-bar-success progress-bar-striped";
$scope.progress = 100;//上传成功之后,将进度条设置为100
}
}, function (){
//这里是error方法
}, function (){
//这里是progress方法
$scope.type = "progress-bar progress-bar-info progress-bar-striped";
$http({
url:"",
method: "get"
}).success(function (res) {
$scope.progress = res;//绑定进度条的值
})
});

上传部分代码(只需要关注设置session的地方

public Map<String, Object> batchModify(InputStream inputStream,HttpSession session) {
Map<String, Object> res = new HashMap<>();
Workbook workbook = null;
try {
workbook = Util.createWorkbook(inputStream);
} catch (InvalidFormatException | IOException e) {
e.printStackTrace();
}
session.setAttribute("progress", 5);//解析成功后我将进度设置为5
Sheet sheet = workbook.getSheetAt(0);
Map<String, Object> roleWithPages = new HashMap<>();
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row r = sheet.getRow(i);
if (r == null || r.getCell(0) == null || r.getCell(1) == null)
continue;
Set<Page> pages = null;
if (roleWithPages.get(r.getCell(0).toString()) == null) {
pages = new HashSet<>();
} else {
pages = (Set<Page>) roleWithPages.get(r.getCell(0).toString());
}
Page p = new Page();
p.setId(Math.round(r.getCell(1).getNumericCellValue()));
pages.add(p);
roleWithPages.put(r.getCell(0).toString(), pages);
session.setAttribute("progress", 5 + i*90/sheet.getLastRowNum());
//我将处理文件主体进度总量设置为90(5是加上解析部分的进度)
}
List<Role> roles = new ArrayList<>();
for (String rolename : roleWithPages.keySet()) {
Role role = repo.findByName(rolename);
role.setPages((Set<Page>) roleWithPages.get(rolename));
roles.add(role);
}
repo.save(roles);
session.setAttribute("progress", 100);//保存之后将进度设置为100
res.put("msg", "数据导入成功!");
return res;
}

进度条部分代码,很简单,就是读Session中progress的值

public int getProgress(HttpServletRequest request){
return (int) request.getSession().getAttribute("progress");
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

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