您的位置:首页 > 编程语言 > Java开发

spring MVC文件上传和实时进度提醒

2016-03-17 09:24 741 查看
http://www.myext.cn/extDetail/a_478.html

@RequestMapping(value = "/getProgress.do", method = RequestMethod.POST, produces = { "application/json" })
@ResponseBody
public Double getProgress(HttpServletRequest request, HttpServletResponse response) {
if (request.getSession().getAttribute("upload_ps") == null) {
return 0.00;
}
ProgressEntity ps = (ProgressEntity) request.getSession().getAttribute("upload_ps");
Double percent = 0d;
if (ps.getpContentLength() != 0L) {
percent = (double) ps.getpBytesRead() / (double) ps.getpContentLength() * 1.0d; // 百分比
if (percent != 0d) {
DecimalFormat df = new DecimalFormat("0.00");
percent = Double.parseDouble(df.format(percent));
}
}
return percent;
}

@RequestMapping(value = "/upLoadFiledir.do", method = RequestMethod.POST, produces = { "application/json" })
@ResponseBody
public void upLoadFile(HttpServletRequest request, @RequestParam("file") MultipartFile[] file) {
System.out.println("开始");
// 文件保存路径
String path = request.getSession().getServletContext().getRealPath("upload");
for (int i = 0; i < file.length; i++) {
String fileName = file[i].getOriginalFilename();
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try {
file[i].transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}


<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
function progress(){
$.post('<%=request.getContextPath()%>/publicdoc/getProgress.do',{},function(data){
$("#progress").attr("data-percent",data*100+"%");
$("#progress-bar").width(data*100+"%");
});
}
var InterValObj;
function doUpload() {
layer.open({
type: 1,
content:  $('#progress'),
area: ['400px', '200px'],
title:'上传文件',
end:function(){//层销毁回调函数
$("#progress").attr("data-percent","0%");
$("#progress-bar").width("0%");
},
closeBtn: 2
});
var formData = new FormData($("#form")[0]);
InterValObj = window.setInterval(progress, 500); //启动计时器,1秒执行一次
$.ajax({
url: '<%=request.getContextPath()%>/publicdoc/upLoadFiledir.do' ,
type: 'POST',
data: formData,
async: true,
cache: true,
contentType: false,
processData: false,
success: function (returndata) {
layer.msg("上传成功",{icon:6});
$("#progress").attr("data-percent","100%");
$("#progress-bar").width("100%");
window.clearInterval(InterValObj);//停止计时器
},
error: function (returndata) {
}
});
}
</script>
<form id="form" enctype="multipart/form-data">
选择文件:<input type="file" name="file" multiple="multiple" id="file">
<input type="button" value="提交" onclick="doUpload()">
</form>

<div class="progress" data-percent="0%" id="progress" style="width: 300px;display: none;margin: auto;margin-top: 50px">
<div class="progress-bar" style="width:0%;" id="progress-bar"></div>
</div>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  上传