大文件上传 +进度条显示+java后端接收
前端代码
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#progress{
height:10px;
width:500px;
border: 1px solid gold;
position: relative;
border-radius: 5px;
}
#progress .progress-item{
height:100%;
position: absolute;
left:0;
top:0;
background: chartreuse;
border-radius: 5px;
transition: width .3s linear;
}
</style>
</head>
<body>
文件上传框<br>
<input type="file" id="file"><br>
显示进度条<br>
<div id="progress">
<div class="progress-item"></div>
</div>
上传成功后的返回内容<br>
<span id="callback"></span>
</body>
<script>
//首先监听input框的变动,选中一个新的文件会触发change事件
document.querySelector("#file").addEventListener("change",function () {
//获取到选中的文件
var file = document.querySelector("#file").files[0];
console.log("file:"+file);
//创建formdata对象
var formdata = new FormData();
formdata.append("file",file);
//创建xhr,使用ajax进行文件上传
var xhr = new XMLHttpRequest();
xhr.open("post","XXX/Upload.do");//你自己的后端接口
//回调
xhr.onreadystatechange = function () {
if (xhr.readyState==4 && xhr.status==200){
document.querySelector("#callback").innerText = xhr.responseText;
console.log(xhr.responseText);
}
}
//获取上传的进度 每0.5秒获取一次
xhr.upload.onprogress = function (event) {
if(event.lengthComputable){
var percent = event.loaded/event.total *100;
document.querySelector("#progress .progress-item").style.width = percent+"%";
console.log(percent);
}
}
//将formdata上传
xhr.send(formdata);
});
</script>
</html>
java后端代码 这里我使用的struts2
import java.io.File;
import java.io.IOException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import net.sf.json.JSONObject;
public class EntityServlet1 extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
private String uploadPath = "D:\\temp"; // 上传文件的目录
File tempPathFile;
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws IOException,ServletException{
System.out.println("2222");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
System.out.println("1111");
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
factory.setRepository(tempPathFile);// 设置缓冲区目录
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(2024*2024*2024); // 设置最大文件尺寸,这里是4MB
List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
System.out.println(items);
Iterator<FileItem> i = items.iterator();
while (i.hasNext()) {//获取域中传入的普通参数
FileItem fi = i.next();
String fileName = fi.getName();
File savedFile = new File(uploadPath, fileName);
System.out.println("upload succeed111");
fi.write(savedFile);
}
System.out.print("上传成功");
} catch (Exception e) {
}
JSONObject json = new JSONObject();
json.accumulate("code", "0");
response.getWriter().write(json.toString());
}
}
我也是看了很多的教程这里使用的servlet的方式,只为获取request方便一些,这里需要注意一点 使用struts2框架的话拦截器会拦截你的文件信息 原因是struts2会改变reqeust的类型,由HttpServletRequest变成MultiPartRequestWrapper 导致
List items = upload.parseRequest(request);// 得到所有的文件 为空
所以这里需要添加一个action为
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest;
public class MyMultiPartRequest extends JakartaMultiPartRequest {
public void parse(HttpServletRequest request, String arg1) throws IOException {
String url = request.getRequestURI().toString();//取得请求的URL
//判断上传方式
//此步的目的是struts2会自动拦截上传请求
if(url.indexOf("demo/Upload.do")>0){
//不需要struts2的处理
System.out.println("进度上传");
}else{
//需要struts2的处理,调用回父类的方法
super.parse(request, arg1);
}
}
}
然后在struts.xml下引入就可以了
<bean type="org.apache.struts2.dispatcher.multipart.MultiPartRequest"
name="myMultiPartRequest" class="com.app.demo.web.action.MyMultiPartRequest"
scope="default" optional="true"/>
<constant name="struts.multipart.handler" value="myMultiPartRequest" />
这样就可以正常上传文件了。
还有就是要添加jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>