1.先上效果图
1.1弹出附件框
1.2选择文件,点击上传(这里做了一个简单的校验)
1.3点击上传
1.4上传成功 刷新列表
2. 知识点准备
2.1XMLHttpRequest
2.2H5 progress
2.3Springmvc
2.4Maven项目下需要的Jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
3. 项目实施
3.1前台代码(这里用到的是bootstrap的模态窗)
<div class="modal-body">
<div>
<p>已存在附件列表</p>
<!--
<div class="row" id="fuJiaList">
</div>
-->
<table class="table table-bordered" >
<tbody id="fuJiaList">
</tbody>
</table>
</div>
<hr/>
<div style="margin-bottom: 5px;"><b>上传文件</b>(文件最大不能超过5M)</div>
<div class="row">
<label class="col-sm-4">请选择要上传的文件</label>
<div class="col-sm-8">
<input type="file" id="fileToUpload" name="fileToUpload" onchange="fileSelected();">
</div>
<div class="col-sm-12" id="fileName"></div>
<div class="col-sm-12" id="fileSize"></div>
<div class="col-sm-12" id="fileType" style="margin-bottom: 5px;"></div>
<div class="col-sm-4">
<input type="button" onclick="uploadFile()" id="uploadFileButton" value="上传"
disabled="false" class="btn btn-info btn-sm"/>
</div>
<div class="col-sm-12" id="progressNumber"></div>
<div class="col-sm-12" id="divForProgress" style="display:none">
<progress value="0" max="100" id="proDownFile" style="width: 567px;border-radius: 2px; border-left: 1px #ccc solid; border-right: 1px #ccc solid; border-top: 1px #aaa solid; background-color: #eee;">
</progress>
</div>
</div>
<input type="hidden" id="FuJia_courseId" name="courseId">
</div>
3.2前台页js代码(XMLHttpRequest)
function fileSelected() {
var file = document.getElementById('fileToUpload').files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
if(file.size > 1024 * 1024 * 5){
alert("文件大小超过5M,不能上传!");
$("#uploadFileButton").attr("disabled","false");//文件过大时上传按钮不可
}else{
$("#uploadFileButton").removeAttr("disabled");
}
}
}
function uploadFile() {
var id= $("#id").val();
var fd = new FormData();
fd.append("file", document.getElementById('fileToUpload').files[0]);
fd.append("id",id);//添加参数
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);//添加监听 更新进度条
xhr.addEventListener("load", uploadComplete, false);//添加完成监听
xhr.addEventListener("error", uploadFailed, false);//添加错误监听
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "URL");//URL改成你要上传的Action
xhr.send(fd);//发送文件到后台
}
function uploadProgress(evt) {
var objPro=document.getElementById('proDownFile');
//显示进度条
$("#divForProgress").removeAttr("style");
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = "已经上传"+percentComplete.toString() + '%';
objPro.value=percentComplete.toString();
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}
//上传成功以后回调函数
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
if( evt.target.responseText =="Y"){
alert("上传成功!");
}
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
3.3后台代码(Springmvc)
@RequestMapping("/fileupdate")
@ResponseBody
public String addFuJia(Integer id,HttpServletRequest request,@RequestParam("file") CommonsMultipartFile file){
try {
if(file.getSize()!=0){
//文件上传
String pathToBeSaved="/fileUpLoad"+file.getOriginalFilename();
String path=request.getSession().getServletContext().getRealPath("/")+pathToBeSaved;
File newFile=new File(path);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(newFile);
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Y";
}
扫描二维码关注公众号,回复:
2704897 查看本文章
![](/qrcode.jpg)