网上看到别人发过的一个java上传的代码,自己写了个完整的,附带源码
项目环境:jkd7、tomcat7、
jar包:commons-fileupload-1.2.1.jar、commons-io-1.4.jar
项目结构:
index.jsp 代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML> <html> <head> <base href="<%=basePath%>"> <title>java进行文件上传,带进度条</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <script type="text/javascript" src="js/jquery-1.8.3.js"></script> <script type="text/javascript"> var over = false; var inter; function upload(){ over = false; $("#state").html("") $("#progress").css("width","0") $("input[type=submit]").attr("disabled",true); $("#progress").css("width","0%"); $("#state").html("正在上传... 总大小:0MB,已上传:0MB,0%,已用时:0秒,剩余时间:0秒,速度:0KB/S"); inter = setInterval(req,1000); } function req(){ //如果上传已经完成 if(over){ clearInterval(inter); return; } var url = "upload/AjaxServlet"; $.get(url,function(date){ var state = date.split("-"); $("#state").html("正在上传... 总大小:"+state[4]+"MB,已上传:"+state[3]+"MB,"+state[2]+"%,已用时:"+state[0]+"秒,剩余时间:"+state[5]+"秒,速度:"+state[1]+"KB/S"); $("#progress").animate({width:state[2]+"%"},500); if(state[3] == state[4]){ over = true; $("input[type=submit]").attr("disabled",false); $("#state").html("上传已完成,总大小:"+state[4]+"MB,已上传:"+state[3]+"MB,"+state[2]+"%,已用时:"+state[0]+"秒,剩余时间:"+state[5]+"秒,速度:"+state[1]+"KB/S"); } }); } </script> </head> <body> <form action="servlet/Upload" method="post" enctype="multipart/form-data" target="upload_iframe" onsubmit="upload()"> <p><input type="file" name="file" id="file"></p> <p><input type="submit" value="上传文件"></p> </form> <iframe name="upload_iframe" width="0" height="0" frameborder="0"></iframe> <div id="state"> </div> <div id="progress" style="background: #728820; height: 10px; width: 0"> </div> </body> </html>