javaweb实现文件上传,前端与后台的结合实现

大家好,这是原创的文件上传源码哦。
希望给大家带来参考价值。
阅读注意:
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!!!):

`<form id="fileform"  method="post" action="UploadFile" name="fileform" enctype="multipart/form-data">
			<br> <%=session.getAttribute("user")+"  " %>请您选择上传文件:&nbsp;&nbsp;&nbsp;&nbsp; <input type="file" name="file" id="file" style="border: 1px solid; margin: 5px; background-color: #eeeeee;" /> <br> <br>
			<div style="text-align: left; margin-left: 120px;">
				<div>注意:文件不能大于2000M,登录后在传文件</div>
				当前上传进度:
				<div style="border-radius:30px;margin-top: 10px; background-color: #aaeeaa; height: 20px; width: 500px; border: 2px solid snow">
					<div style="border-radius:30px;background-color: black; height: 20px; width: 0px;" id="pg"></div>
				</div>
				上传情况:&nbsp; <span id="pn"></span>
			</div>
			<br> <input type="button" value="上传" onclick="dealfile(fileform)" /> &nbsp;&nbsp;&nbsp;&nbsp; <input type="reset" value="重新上传(重置)" />
		</form>

Java后台:(注意与前端文件名字的统一)
1.一个输出session的process的jsp(简单)

`<body>
	<%
	response.getWriter().write(session.getAttribute("process").toString());
	%>
</body>`

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

<body>
<% session.setAttribute("cancel", "true"); %>
</body>

`

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);
	}

}

完结。

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值