带进度条的上传
可以用第三方的js组件
可以用flash
可以用h5(只能实现单文件上传)
Html5 Progress Event
对于Html5 Progress Events规范,Html5 Progess Events提供了下列与本次讨论相关的信息
- total - 总的字节数
- loaded - 到目前为止上传的字节数
- lengthComputable - 可计算的已上传字节
Html5 上传 用XMLHttpRequest
浏览器支持情况
支持这一特性的浏览器最低版本
- Firefox 4.0 beta 6
- Chrome 6
- Safari 5.02
IE 9 Beta and Opera 10.62 不支持这一特性
简单案例
test.js文件
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; } } function uploadFile() { var fd = new FormData(); fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]); 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", "html5.action");//修改成自己的接口 xhr.send(fd); } function uploadProgress(evt) { if (evt.lengthComputable) { var percentComplete = Math.round(evt.loaded * 100 / evt.total); document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%'; } else { document.getElementById('progressNumber').innerHTML = 'unable to compute'; } } function uploadComplete(evt) { /* 服务器端返回响应时候触发event事件*/ alert(evt.target.responseText); } 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."); }
jsp文件
<%@ 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="${pageContext.request.contextPath }/js/test.js"></script>
<link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css"> <title>Insert title here</title> </head> <body> <form id="form1" enctype="multipart/form-data" method="post" action="Upload.aspx"> <div class="row"> <label for="fileToUpload">Select a File to Upload</label><br /> <input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();"/> </div> <div id="fileName"></div> <div id="fileSize"></div> <div id="fileType"></div> <div class="row"> <input type="button" onclick="uploadFile()" value="Upload" /> </div> <div id="progressNumber"></div> </form> </body> </html>
1.后台不需要做任何改变,依然沿用原始上传下载的方法即可
2.进度条的样式没有给定,可以自己画css也可以用js-ui样式