java进行文件上传,带进度条
网上看到别人发过的一个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>
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进行文件上传,带进度条的更多相关文章
- atitit. 文件上传带进度条 atiUP 设计 java c# php
atitit. 文件上传带进度条 atiUP 设计 java c# php 1. 设计要求 1 2. 原理and 架构 1 3. ui 2 4. spring mvc 2 5. springMVC.x ...
- atitit.文件上传带进度条的实现原理and组件选型and最佳实践总结O7
atitit.文件上传带进度条的实现原理and组件选型and最佳实践总结O7 1. 实现原理 1 2. 大的文件上传原理::使用applet 1 3. 新的bp 2 1. 性能提升---分割小文件上传 ...
- Struts2文件上传带进度条,虽然不是很完美
好久没有写东西,最近在做个项目,要用到文件h 传的,以前虽然也做上传,但是总觉得不好用 ,现在和队友合作做了一个带进度条的上传,觉得还行~~和大家分享一下. 首先说一下大概是这样实现的,在我们平时的上 ...
- Flex4/Flash多文件上传(带进度条)实例分享
要求 必备知识 本文要求基本了解 Adobe Flex编程知识和JAVA基础知识. 开发环境 MyEclipse10/Flash Builder4.6/Flash Player11及以上 演示地址 演 ...
- Springboot 文件上传(带进度条)
1. 相关依赖 pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http ...
- HTML5 + AJAX ( jQuery版本 ) 文件上传带进度条
页面技术:HTML5 + AJAX ( jQuery) 后台技术:Servlet 3.0 服务器:Tomcat 7.0 jQuery版本:1.9.1 Servlet 3.0 代码 package or ...
- springMVC+ajax 文件上传 带进度条
前端代码: <form id= "uploadForm"> <p >指定文件名: <input type="text" name= ...
- php实现大文件上传带进度条
1.使用PHP的创始人 Rasmus Lerdorf 写的APC扩展模块来实现(http://pecl.php.net/package/apc) APC实现方法: 安装APC,参照官方文档安装,可以使 ...
- struts2多文件上传(带进度条)demo+说明
利用plupload插件实现多文件上传,实现图片: 在jsp写入js代码: z<%@ page language="java" contentType="text/ ...
- html5 文件上传 带进度条
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/ ...
随机推荐
- .Net缓存管理框架CacheManager
using System; using CacheManager.Core; namespace ConsoleApplication { class Program { static void Ma ...
- ORA-14450: attempt to access a transactional temp table already in use
在ORACLE数据中修改会话级临时表时,有可能会遇到ORA-14550错误,那么为什么会话级全局临时表会报ORA-14450错误呢,如下所示,我们先从一个小小案例入手: 案例1: SQL> CR ...
- Fedora 23安装配置mysql数据库,修改初始密码及登陆
下载MySQL5.7.9 yum仓库 wget http://dev.mysql.com/get/mysql57-community-release-fc23-7-noarch.rpm rpm -iv ...
- C++智能指针详解
本文出自http://mxdxm.iteye.com/ 一.简介 由于 C++ 语言没有自动内存回收机制,程序员每次 new 出来的内存都要手动 delete.程序员忘记 delete,流程太复杂,最 ...
- Linux IPC socket 广播,组播
getsockopt()/setsockopt() //获得sockfd指向的socket的属性 int getsockopt(int sockfd, int level, int optname, ...
- android 发送短信功能
private void sendSMS(String num,String smsBody) { String phoneNum = "smsto:" + num; Uri sm ...
- ELF Format 笔记(十三)—— 段权限
ilocker:关注 Android 安全(新手) QQ: 2597294287 一个可被系统加载的程序至少拥有一个可加载段.当系统创建可加载段的内存映像时,会根据 p_flags 赋予一定的访问权限 ...
- linux(64位的系统)下nasm进行汇编链接时出现的问题
出现问题: $nasm -f elf hello.asm -o hello.o $ld -s hello.o -o hello ld: i386 architecture of input file ...
- 【php+mysql】博客分页制作思路
1.首先需要初始化设置每页显示的文章数$page_size,mysql数据库中总的文章数$arc_size,页面数$page 2.利用分页公式 (当前页数 - 1 )X 每页条数 , 每页条数Sele ...
- WinCE非通用调试工具汇总
WinCE-IIC调试助手(S3C2410) http://www.cnblogs.com/we-hjb/archive/2008/10/19/1314562.html WinCE下音频频谱显示(TD ...