阅读注意:

1.只给出了关键代码(但是绝大部分代码),需要自己小小润色一下。

2.代码分为前端与后台,

3.本人初学者,有错,望您指出。

4.后台需要jar包支持:

commons-io-1.3.2.jar

commons-fileupload-1.2.1.jar

5.表单属性设置:

enctype=“multipart/form-data”

ajax请求头设置:

this.httpRequest.setRequestHeader(“Content-Disposition”,“multipart/form-data”);

前端代码:

采用ajax获取(自己写的ajax,原理性强):

ajax.js(ajax重构)

/**
* Ajax重构 多次使用,代码重构
*/
var timer = null;
var net = new Object();
// ajax重构
net.AjaxRequest = function(url, dealfun, onerror, method, params) {
// 创建XMLHttpRequest
this.httpRequest = null;
// 回调函数
this.onload = dealfun;
// 错误处理
this.onerror = (onerror) ? onerror : this.defaultError;
// 向服务器发送请求(创建连接)
this.loadrequest(url, method, params);
}
// 向服务器发送请求(创建连接)
net.AjaxRequest.prototype.loadrequest = function(url, method, params) {
// 创建XMLHttpRequest
if (window.XMLHttpRequest)
this.httpRequest = new XMLHttpRequest();
else if (window.ActiveXObject)
this.httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
if (this.httpRequest) {
try {
// 回调函数
var deal = this;
this.httpRequest.onreadystatechange = function() {
net.AjaxRequest.deal.call(deal);
};
// 创建XMLHttpRequest成功,发送请求
this.httpRequest.open(method, url, true);
this.httpRequest.setRequestHeader("Content-Disposition","multipart/form-data");
// 发送params
this.httpRequest.send(params);
} catch (e) {
this.onerror.call(this);
}
}
}
//回调
net.AjaxRequest.deal = function() {
if (this.httpRequest.readyState == 4)
if (this.httpRequest.status == 200)
this.onload.call(this);
else
this.onerror.call(this);
}
// 默认错误处理
net.AjaxRequest.prototype.defaultError = function() {
alert("默认错误处理:回调状态码:" + this.httpRequest.readyState + "错误状态码:"
+ this.httpRequest.status);
//window.clearInterval(timer);
//timer = null;
}
html.js(前端页面js)
var timer = null;
// 上传文件处理结果回调,ajax,json,原型
function dealupload() {
var p = this.httpRequest.responseText;
var p1 = p.substr(0, 5);
if (p1 == "完成上传!") {
clearInterval(timer);
timer = null;
alert(p1);
return true;
} else {
document.getElementById("pn").innerHTML = p;
document.getElementById("pg").style.width = (p1 * (500 / 100))
.toString()
+ "px";
}
}
// 上传文件
function doupload() {
var load = new net.AjaxRequest("showprocess.jsp?nocache="
+ new Date().getTime(), dealupload, null, "POST");
}
function dealcancelupload() {
alert("你取消了上传此文件!!!");
}
// 取消文件上传
fileform.onreset = function() {
document.getElementById("pg").style.width = "0px";
var no = new net.AjaxRequest("cancelupload.jsp?nocache="
+ new Date().getTime(), dealcancelupload, null, "POST");
}
// 文件预处理上传
function dealfile(fileform) {
var file = document.getElementById("file");
if (document.fileform.file.value == "") {
alert("请选择上传文件!!!");
return false;
}
var filesize = file.files[0].size;
if (filesize > 2000 * 1024 * 1024) {
alert("请选择小于2000MB的文件!!!");
return false;
} else {
timer = window.setInterval("doupload()", 300);
fileform.submit();
}
}

前端表单代码(记得引入以上js!!!):

`请您选择上传文件:

注意:文件不能大于2000M,登录后在传文件

当前上传进度:

上传情况:

Java后台:(注意与前端文件名字的统一)

1.一个输出session的process的jsp(简单)

`

`

2.一个获取session的cancel的jsp(简单)

`

3.上传类:

package com.uploadfile;
import java.io.*;
import javax.servlet.*;
import java.util.Iterator;
import java.util.List;
import org.apache.tomcat.util.http.fileupload.*;
@WebServlet(name = "UploadFile", value = "/UploadFile")
public class UploadFile extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO 自动生成的方法存根
this.uploadfile(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO 自动生成的方法存根
this.uploadfile(req, resp);
}
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
// TODO 自动生成的方法存根
super.service(arg0, arg1);
}
@Override
public void destroy() {
// TODO 自动生成的方法存根
super.destroy();
}
@SuppressWarnings("rawtypes")
public void uploadfile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
HttpSession session = req.getSession();
//取消文件上传标志
session.setAttribute("cancel", "false");
//错误信息
String error = "";
//前端响应
session.setAttribute("process", "浏览器上传文件中...请耐心等待");
//创建
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upl = new ServletFileUpload(fac);
try {
// 解析时间需更新客户端是否取消上传
List items = upl.parseRequest(new ServletRequestContext(req));
Iterator it = items.iterator();
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
if (!item.isFormField()) {
if (item.getName() != null && !item.getName().equals("")) {
long loadsize = item.getSize();
String name = item.getName();
File temp1 = new File(name);
//服务器创建写入文件
File temp = new File(req.getSession().getServletContext().getRealPath("/LoadFile"), temp1.getName());
// 存入文件
// 客户端上传文件读取
InputStream tempr = item.getInputStream();
byte[] b = new byte[1024];
// 上传文件存入服务器
FileOutputStream wf = new FileOutputStream(temp);
// 上传进度
double process = 0;
int length = 0;
boolean flag = true;
while ((length = tempr.read(b)) != -1) {
if (session.getAttribute("cancel") == "true") {
//如果取消了上传
session.setAttribute("cancel", "false");
session.setAttribute("process", "取消上传中。");
wf.flush();
wf.close();
flag = false;
if (temp.exists()) {
temp.delete();
}
break;
}
process += (length / (double) loadsize) * 100D;
wf.write(b);
session.setAttribute("process", "服务器写入进度:"+(float) process + "%");
}
if (flag == true) {
wf.flush();
wf.close();
session.setAttribute("process", "完成上传!");
}
Thread.sleep(500);
}
}
}
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
error = "服务器出错";
}
if (!error.equals("")) {
session.setAttribute("process", error + "->失败");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
}
}
//完成服务重定向
//req.getRequestDispatcher("WEB-INF/login/welcome.jsp").forward(req, resp);
}
}

完结。