html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>中期成果提交</title>
<link rel="stylesheet" href="../../layui/css/layui.css">
<link rel="stylesheet" href="../css/style.css">
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet"
href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<style>
html,body{background: #fff;}
.article5 {padding: 10px;min-height:330px;border:1px solid #e6e6e6;}
.article5 .arR span { line-height: 32px; }
.article6 { height: 32px; padding-left: 40px; margin-bottom: 15px; }
.article6 .arR span { float: right;}
.article9 { width: 620px; margin: 25px auto 0; height: 48px; }
.article9 span { width: 200px; height: 30px; border-radius: 20px; line-height: 30px; text-align: center; font-size: 13px; cursor: pointer}
.article9 span.arL { background: #0fa4f8; color: #fff; }
.article9 span.arR { border: 1px solid #eee; color: #999; }
</style>
</head>
<body>
<#include "/head2.ftl"/>
<div class="home_body">
<#include "/left.ftl"/>
<div class="home_right">
<input type="hidden" name="paid" value="${paId}" class="layui-input">
<span style="color:#0c87ef">选择附件</span> <span style="color:#0c87ef" id="add">添加</span>
<h6>请上传小于10MB的doc,docx,xls,xlsx,txt,PDF格式附件。</h6>
<form id="uploadForm">
<!-- 由于使用了ssm框架,后台接收是用name绑定的,注意name和后台一致 -->
<input type="file" id="file" name="file" class="file" οnchange="fileChange(this);"/>
</form>
<div class="progress" style="width: 40%">
<div id="progressactive"
class="progress-bar progress-bar-striped active" role="progressbar"
aria-valuenow="45" aria-valuemin="0" aria-valuemax="100"
style="width: 0%"></div>
</div>
<span id="sr-only"></span>
<article class="article9 clearfix" >
<span class="fl arL" id="submit" οnclick="UpladFile()">提交</span>
</article>
</div>
</div>
<#include "/foot.ftl"/>
</div>
</body>
<script src="../../layui/layui.js"></script>
<script src="../js/index.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js"></script>
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script
src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
<script type="text/javascript">
var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
function fileChange(target,id) {
var fileSize = 0;
var filetypes =[".rar",".txt",".zip",".doc",".ppt",".xls",".pdf",".docx",".xlsx"];
var filepath = target.value;
var filemaxsize = 1024*10;//2M
if(filepath){
var isnext = false;
var fileend = filepath.substring(filepath.lastIndexOf("."));
if(filetypes && filetypes.length>0){
for(var i =0; i<filetypes.length;i++){
if(filetypes[i]==fileend){
isnext = true;
break;
}
}
}
if(!isnext){
alert("不接受此文件类型!");
target.value ="";
return false;
}
}else{
return false;
}
if (isIE && !target.files) {
var filePath = target.value;
var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
if(!fileSystem.FileExists(filePath)){
alert("附件不存在,请重新输入!");
return false;
}
var file = fileSystem.GetFile (filePath);
fileSize = file.Size;
} else {
fileSize = target.files[0].size;
}
var size = fileSize / 1024;
if(size>filemaxsize){
alert("附件大小不能大于"+filemaxsize/1024+"M!");
target.value ="";
return false;
}
if(size<=0){
alert("附件大小不能为0M!");
target.value ="";
return false;
}
}
$("#add").click(function(){
var p='<input type="file" id="file" name="file" class="file" οnchange="fileChange(this);"/>';
$("#uploadForm").append(p);
})
function UpladFile() {
var paid=$(" input[ name='paid' ] ").val();
var fileObj = document.getElementById("file").files[0]; // js 获取文件对象
var FileController = "upResult.do?type=middle&paid="+paid; // 接收上传文件的后台地址
// FormData 对象
var form = new FormData($("#uploadForm")[0]);//创建一个form对象
// XMLHttpRequest 对象
var xhr = new XMLHttpRequest();//创建XMLHttpRequest对象
xhr.open("post", FileController, true);//打开连接,(访问类型,地址,是否异步)
xhr.onload = function() {//请求完成后执行 里面可用
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
//alert(xhr.responseText);//后台返回的数据
alert("上传成功");
window.location.href = "cgtj.do";
} else {
alert("Request was unsuccessful: " + xhr.status);//状态
//0 UNSENT (未打开),1 OPENED (未发送),2 HEADERS_RECEIVED (已获取响应头),3 LOADING (正在下载响应体),4 DONE (请求完成)
}
};
xhr.upload.addEventListener("progress", progressFunction, false);//添加上传监听器方法
xhr.send(form);//发送请求
}
function progressFunction(evt) {
var progressBar = document.getElementById("progressactive");//获取进度条对象
var percentageDiv = document.getElementById("sr-only");//获取展示进度数据对象
if (evt.lengthComputable) {
var max = evt.total;//文件总大小
var loaded = evt.loaded;//已上传文件大小
console.log(max);
progressBar.style.width = Math.round(loaded / max * 100) + "%";
percentageDiv.innerHTML = Math.round(loaded / max * 100) + "%";
if (evt.loaded == evt.total) {
percentageDiv.innerHTML = "上传完成";
}
}
}
</script>
</html>
进度条progross实体文件
public class Progress {
private long bytesRead;
private long contentLength;
private long items;
public long getBytesRead() {
return bytesRead;
}
public void setBytesRead(long bytesRead) {
this.bytesRead = bytesRead;
}
public long getContentLength() {
return contentLength;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public long getItems() {
return items;
}
public void setItems(long items) {
this.items = items;
}
@Override
public String toString() {
return "Progress [bytesRead=" + bytesRead + ", contentLength=" + contentLength + ", items=" + items + "]";
}
}
监听
package com.blue.util;
import org.apache.commons.fileupload.ProgressListener;
import com.blue.beans.ProgressInfo;
public class UploadListener implements ProgressListener {
private static final long UPDATE_THRESHOLD = 35 * 1024L; // 20KB
private long megaBytes = -1;
private ProgressInfo pi = null;
public UploadListener(ProgressInfo pi) {
this.pi = pi;
}
public void update(long pBytesRead, long pContentLength, int pItems) {
try{
Thread.sleep(20);
}catch(Exception ex){
pi.setInProgress(false);
ex.printStackTrace();
}
long mBytes = pBytesRead / UPDATE_THRESHOLD;
if (megaBytes == mBytes && megaBytes > 0) {
return;
}
megaBytes = mBytes;
pi.setBytesRead(pBytesRead);
pi.setFileIndex(pItems);
pi.setTotalSize(pContentLength);
if( pBytesRead + UPDATE_THRESHOLD >= pContentLength){
pi.setCompleted(true);
Util.info("UploadListener",pBytesRead + ";" + pItems + ";" + pContentLength);
Util.info("UploadListener ->> update ","Completed");
}
}
}
controller
@RequestMapping(value = "/html/project/upload.do", method = RequestMethod.POST)
public String upload(HttpServletRequest request,
@RequestParam("file") MultipartFile[] file, ModelMap model) {
HttpSession session = request.getSession();
String token = (String) session.getAttribute("token");
String pa_id = request.getParameter("paid");
String type = request.getParameter("type"); //middle 中期成果 final 末期成功
String path = request.getSession().getServletContext()
.getRealPath("upload");//获取当前项目下的upload
for (int i = 0; i < file.length; i++) {
String fileName = file[i].getOriginalFilename();//获取文件名
// String fileName = new Date().getTime()+".jpg";//替换新名字
System.out.println(path);
File targetFile = new File(path, fileName);//判断文件是否存在,不存在则创建,可创建文件夹
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
try {
//使用transferTo(dest)方法将上传文件写到服务器上指定的文件。
file[i].transferTo(targetFile);//此方法在上传完成后才开始上传
} catch (Exception e) {
e.printStackTrace();
}
}
// model.addAttribute("fileUrl", request.getContextPath() + "/upload/"
// + fileName);
return "index";
}