话不多说直接上代码

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../3rd/jquery-3.2.1.min.js"></script> <style type="text/css"> .modelContent{
width: 380px;
height: 150px;
margin: 100px 200px;
background-color: #FFFFFF;
z-index: 1050;
position: absolute; } .hidden{
display: none;
} .content {
position: relative;
width: 350px;
margin: 30px 20px; } .txt {
height: 22px;
border: 1px solid #cdcdcd;
width: 180px;
vertical-align: middle;
margin: 0;
padding: 0
} .btn {
border: 1px solid #CDCDCD;
height: 24px;
width: 70px;
vertical-align: middle;
margin: 0;
padding: 0
} .file {
position: absolute;
top: 0;
left: 190px;
height: 24px;
filter: alpha(opacity : 0);
opacity: 0;
width: 70px;
vertical-align: middle;
margin: 0;
padding: 0
} .backdrop{
position: fixed;
z-index: 1040;
background-color: #333;
opacity: .5;
width: 100%;
height: 100%;
} .header{
padding: 15px;
border-bottom: 1px solid #e5e5e5;
} .close:focus, .close:hover {
color: #000;
text-decoration: none;
cursor: pointer;
opacity: .5;
} .close{
float: right;
margin-top: -9px;
} </style>
</head> <body>
<!-- 附于body之上的div -->
<div class="hidden backdrop" id="backDiv"></div> <!-- 定义上传按钮 -->
<button type="button" class="btn btn-default" title="导入" id="export">
</button> <!-- 定义上传对话框 -->
<div class="modelContent hidden" id="uploadDialog">
<!-- 标题 -->
<div class="header">
<span class="close">x</span>
</div>
<!-- 内容 -->
<div class="content">
<input type="text" id="textfield" class="txt" disabled="disabled"/>
<input type="button" class="btn" value="浏览..." />
<input type="file" name="file" class="file" id="file" multiple/>
<!-- onchange="document.getElementById('textfield').value=this.value" -->
<input type="submit" id="submit" class="btn" value="上传"/>
</div>
<!-- 上传进度条 -->
<div class="hidden" id="progressDiv" style="margin: 0px 15px;">
<progress id="progressbar" value="0" max="100" style="width: 308px;">
</progress>
<span id="percentage" style="color: blue;"></span>
</div>
</div>
</body> <script type="text/javascript">
$(function(){
$("#export").click(function(){
$("#uploadDialog,#backDiv").removeClass("hidden");
$("body").css("background-color","#fff");
}); //将选择的文件写到text中
$("#file").change(function(e){
var nameArray = [];
var files = $("#file")[0].files;
$.each(files,function(index,val){
nameArray.push(val.name);
});
$("#textfield").val(nameArray.join());
}) //关闭上传对话框
$(".close").click(function(e){
$("#uploadDialog,#backDiv").addClass("hidden");
$("#textfield").val("");
}); //点击上传,由于非form表单上传,因此采用
$("#submit").click(function(e){
//显示进度条
$("#progressDiv").show();
//获取上传文件
var fileObj = $("#file")[0].files[0];
console.log(fileObj);
//使用formdata实现无刷新上传
var formData = new FormData();
formData.append("file",fileObj);
//后台使用springmvc接收请求
var url = "http://localhost:8080/SpringMVCTest/index/fileUpload";
//ajax
var xhr = new XMLHttpRequest();
xhr.open("POST",url,true);
//定义上传对象的进度事件
xhr.upload.onprogress=function(event){
var progressBar = document.getElementById("progressbar") ;
var percentageDiv = document.getElementById("percentage");
if (event.lengthComputable) {
progressBar.max = event.total;
progressBar.value = event.loaded;
percentageDiv.innerHTML = Math.round(event.loaded / event.total * 100)+ "%";
}
}; // //当状态为4,
xhr.onload = function(event){
//获取相应的状态
var data = xhr.responseText;
//关闭进度条,并显示上传成功状态
// $("#progressDiv").addClass("hidden");
//
};
xhr.send(formData);
});
})
</script>
</html>

几点提示:

 1. 模态框的处理中必须增加一个影藏的div,设置其高、宽均为100%,当模态框显示时只需要其z-index的值大于背景div即可。

 2. post的请求体必须使用FormData来传递,否则后台无法接受到文件信息。

后台处理使用springmvc,务必注意以下几点,

 1. 在spring-mvc.xml中配置CommonsMultipartResolver的mutipart解析类

 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="10240000"></property>
</bean>

 2. 如果需要进度条显示,则需要实现进度监听类ProgressListener

 package com.yongcheng.liuyang.listener;

 import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.ProgressListener;
import org.springframework.stereotype.Component; import com.yongcheng.liuyang.model.Progress; @Component
public class FileUploadProgressListener implements ProgressListener {
private HttpSession session;
public void setSession(HttpSession session){
this.session=session;
Progress status = new Progress();//保存上传状态
session.setAttribute("status", status);
}
public void update(long pBytesRead, long pContentLength, int pItems) {
Progress status = (Progress) session.getAttribute("status");
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
status.setpBytesRead(pBytesRead);
status.setpContentLength(pContentLength);
status.setpItems(pItems); } }

3. 如果实现了进度监听接口,则需要将进度信息写到文件的解析类中,因此必须继承CommonsMultipartResolver,覆写parseRequest方法

 package com.yongcheng.liuyang.listener;

 import java.util.List;

 import javax.servlet.http.HttpServletRequest;

 import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver; public class CustomMultipartResolver extends CommonsMultipartResolver { @Autowired
private FileUploadProgressListener progressListener; public void setFileUploadProgressListener(
FileUploadProgressListener progressListener) {
this.progressListener = progressListener;
} @Override
@SuppressWarnings("unchecked")
public MultipartParsingResult parseRequest(HttpServletRequest request)
throws MultipartException {
String encoding = determineEncoding(request);
FileUpload fileUpload = prepareFileUpload(encoding);
progressListener.setSession(request.getSession());
fileUpload.setProgressListener(progressListener);
try {
List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
return parseFileItems(fileItems, encoding);
}
catch (FileUploadBase.SizeLimitExceededException ex) {
throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
}
catch (FileUploadException ex) {
throw new MultipartException("Could not parse multipart servlet request", ex);
}
}
}

 如有问题,欢迎评论留言,共同进步!!

随机推荐

  1. 你不知道的CSS背景—css背景属性全解

    CSS背景在网页设计中使用频率非常高,然而对于这个开发人员很熟悉的CSS属性,却隐藏着许多不为初级开发人员熟知的细节,这篇文章尝试扒开这层不为人知的面纱. 首先列举一下CSS中关于元素背景的所有属性并 ...

  2. 【POJ 3041】Asteroids (最小点覆盖)

    每次选择清除一行或者一列上的小行星.最少选择几次. 将行和列抽象成点,第i行为节点i+n,第j列为节点j,每个行星则是一条边,连接了所在的行列. 于是问题转化成最小点覆盖.二分图的最小点覆盖==最大匹 ...

  3. javascript 倒计时获取验证码

    var wait=60;function reSendCode(id) { var obj = $("#"+id); if (wait == 0) { obj.attr(" ...

  4. HDU 1045 - Fire Net (最大独立集)

    题意:给你一个正方形棋盘.每个棋子可以直线攻击,除非隔着石头.现在要求所有棋子都不互相攻击,问最多可以放多少个棋子. 这个题可以用搜索来做.每个棋子考虑放与不放两种情况,然后再判断是否能互相攻击来剪枝 ...

  5. windows 8.1 pro X64安装中断

    用PE安装windows 8.1 pro X64 ISO镜像,快完成的时候卡在蓝色背景那不动了,等待了大概30min强制重启了. 奇怪的是,居然进去了,不过很慢.配置了一段时间终于看到桌面了,关机,失 ...

  6. FFmpeg发送流媒体的命令(UDP,RTP,RTMP)

    http://blog.csdn.net/leixiaohua1020/article/details/38283297

  7. DRBD脑裂解决方法

    1.查看主服务器 [root@master ~]# /etc/init.d/drbd status drbd driver loaded OK; device status: version: (ap ...

  8. Bounce 弹飞绵羊

    Bounce 弹飞绵羊 题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=2002 分块 将整个大区间分成若干块,每个点维护到下一个块需要跳的次 ...

  9. 2PC/3PC/Paxos

    在分布式系统中,一个事务可能涉及到集群中的多个节点.单个节点很容易知道自己执行的事务成功还是失败,但因为网络不可靠难以了解其它节点的执行状态(可能事务执行成功但网络访问超时). 若部分节点事务执行失败 ...

  10. Sublime Text 3 插件

    1.快捷键:ctrl+shift+P 2.输入install package,选择install package 3.输入需要安装的插件,选择安装 4.重启sublime 1. 格式化 html-cs ...