java进行文件上传,带进度条

时间:2022-09-30 14:32:19

网上看到别人发过的一个java上传的代码,自己写了个完整的,附带源码

项目环境:jkd7、tomcat7、

jar包:commons-fileupload-1.2.1.jar、commons-io-1.4.jar

项目结构:

java进行文件上传,带进度条

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>

index.jsp

package com.sevennight.entity

 package com.sevennight.entity;

 public class Upload {
private long totalSize; //总大小
private long startTime = System.currentTimeMillis(); //开始时间
private long uploadSize; //已上传的大小
public long getTotalSize() {
return totalSize;
}
public void setTotalSize(long totalSize) {
this.totalSize = totalSize;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public long getUploadSize() {
return uploadSize;
}
public void setUploadSize(long uploadSize) {
this.uploadSize = uploadSize;
}
}

Upload.java

com.sevennight.lister

package com.sevennight.lister;

import org.apache.commons.fileupload.ProgressListener;

import com.sevennight.entity.Upload;

public class UploadLister implements ProgressListener{
private Upload upload = null; public UploadLister(Upload upload){
this.upload = upload;
} public void update(long uploadSize,long totalSize,int items) {
upload.setUploadSize(uploadSize);
upload.setTotalSize(totalSize);
}
}

UploadLister.java

com.sevennight.servlet

 package com.sevennight.servlet;

 import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.sevennight.entity.Upload; @SuppressWarnings("serial")
public class AjaxServlet extends HttpServlet { public AjaxServlet() {
super();
} public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Cache-Control", "no-store");// 禁止浏览器缓存
response.setHeader("Pragrma", "no-cache");// 禁止浏览器缓存
response.setDateHeader("Expires", 0);// 禁止浏览器缓存
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Upload upload = null;
upload = (Upload)request.getSession().getAttribute("upload");
if(null == upload)
return;
long currentTime = System.currentTimeMillis();
//计算已用时,以S为单位
long time = (currentTime - upload.getStartTime()) / 1000 + 1;
//计算速度,以kb为单位
long speed = (long)(double)upload.getUploadSize() / 1024 / time;
//计算百分比
int percent = (int)((double)upload.getUploadSize() / (double)upload.getTotalSize() * 100);
//已经完成
int mb = (int)upload.getUploadSize() / 1024 / 1024;
//总共有多少
int totalMb = (int)upload.getTotalSize() / 1024 / 1024;
//剩余时间
int shenYu = (int)((upload.getTotalSize() - upload.getUploadSize()) / 1024 / speed);
String str = time+"-"+speed+"-"+percent+"-"+mb+"-"+totalMb+"-"+shenYu;
out.print(str);
out.flush();
out.close();
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} public void init() throws ServletException {
// Put your code here
} }

AjaxServlet.java

 package com.sevennight.servlet;

 import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.sevennight.lister.UploadLister; @SuppressWarnings("serial")
public class Upload extends HttpServlet { public Upload() {
super();
} public void destroy() {
super.destroy();
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} @SuppressWarnings({ "deprecation", "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter(); com.sevennight.entity.Upload upload = new com.sevennight.entity.Upload(); UploadLister lister = new UploadLister(upload); ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); //只是上传监听器
servletFileUpload.setProgressListener(lister); request.getSession().setAttribute("upload", upload); List list = null;
try {
list = servletFileUpload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
} for(Iterator iter = list.iterator(); iter.hasNext();){
//得到文件对象
FileItem fileItem = (FileItem)iter.next();
//是表单才进行处理
if(fileItem.isFormField()){
break;
}
//同意linux和windows的路径分隔符
String name = fileItem.getName().replaceAll("/", "\\");
//得到文件名
int index = name.lastIndexOf("\\");
String fileFileName = "";
if(index == -1){
fileFileName = name;
}else{
fileFileName = name.substring(index + 1);
} InputStream fileInputStream = fileItem.getInputStream(); String path = request.getRealPath("/upload");
System.out.println("上传路径:----->"+path);
//也可不用自己写实现方法直接使用,fileItem.write(uploadFile);
File uploadFile = new File(path,fileFileName);
//首先要确认路径是否存在
uploadFile.getParentFile().mkdirs();
//检查文件是否已经存在
if(!uploadFile.exists()){
//建立文件
uploadFile.createNewFile();
}
FileOutputStream out2 = new FileOutputStream(uploadFile);
//开始copy文件 @SuppressWarnings("unused")
int len = 0;//每次读取的字节数
byte[] bytes = new byte[1024];
while((len = fileInputStream.read(bytes, 0, bytes.length)) != -1){
out2.write(bytes);
}
out2.flush();
out2.close();
fileInputStream.close();
}
out.flush();
out.close();
} public void init() throws ServletException {
} }

Upload.java

xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet>
<servlet-name>AjaxServlet</servlet-name>
<servlet-class>com.sevennight.servlet.AjaxServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>Upload</servlet-name>
<servlet-class>com.sevennight.servlet.Upload</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>AjaxServlet</servlet-name>
<url-pattern>/upload/AjaxServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/servlet/Upload</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>upload.jsp</welcome-file>
</welcome-file-list>
</web-app>

web.xml

源码地址http://pan.baidu.com/s/1i3JxC5v

效果图:

java进行文件上传,带进度条