在页面中听过来上传文件
form表单:
<form onsubmit="getProgress()" action="upFile" method="post" enctype="multipart/form-data">
<input name="file" type="file">
<!-- 进度条 -->
<div class="progress"></div>
<input type="submit">
</form>
提交到servlet,用来接收并保存文件信息
注意:servlet若没有配置注解,则需要在web.xml配置
package com.whbweb.top.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;
import javax.print.attribute.standard.Severity;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.sun.xml.internal.ws.api.server.HttpEndpoint;
import com.whbweb.top.pojo.UploadStatus;
import com.whbweb.top.util.UploadListener;
@WebServlet(urlPatterns = "/upFile")
public class UpFileServlet extends HttpServlet {
/*
* 该servlet实现了文件上传功能
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置编码等
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.write("<!DOCTYPE html>");
out.write("<html>");
out.write("<head>");
out.write("<title>MyHtml.html</title>");
out.write("<meta name=\"content-type\" content=\"text/html; charset=UTF-8\">");
out.write(" </head><body>");
//初始化工厂类
DiskFileItemFactory factory=new DiskFileItemFactory();
//判断是否有文件上传
if(ServletFileUpload.isMultipartContent(req)){
//获取文件保存路径
String path=this.getServletContext().getRealPath("/WEB-INF/upFile/");
//缓存文件路径
File upFile=new File(path+"/tem");
//查看该目录是否存在,不存在则创建
if (!upFile.exists()) {
upFile.mkdirs();
}
//设置缓存路径
factory.setRepository(upFile);
//设置缓存区容量
factory.setSizeThreshold(1024*1024);
//通过工厂建立ServletFileUpload对象
ServletFileUpload upload=new ServletFileUpload(factory);
//创建一个用于存放进度信息的java been对象
UploadStatus status=new UploadStatus();
//设置精度监听,UploadListener为实现了ProgressListener的java been对象,用于跟新进度
upload.setProgressListener(new UploadListener(status));
//在这里将status对象放入session域中
req.getSession().setAttribute("status", status);
//设置存放文件区域空间
upload.setFileSizeMax(1024*1024*1024);
//设置文件编码
upload.setHeaderEncoding("UTF-8");
try {
//得到所有Form提交的表单记录
List<FileItem> list=upload.parseRequest(req);
for(FileItem item:list){
if (item.isFormField()) {//表示一个普通Form元素
out.write("<div>");
out.write(item.getFieldName()+":");
out.write("</div>");
out.write("<div>");
out.write(item.getString());
out.write("</div>");
}else{//表示文件域
Long l=item.getSize();
System.out.println(l);
String name=item.getName();
File saveFile=new File(path+"/"+name);
InputStream is=item.getInputStream();
FileOutputStream fos=new FileOutputStream(saveFile);
byte[] bs=new byte[1024*1024*1024];
int n=0;
while ((n=is.read(bs, 0, bs.length))!=-1) {
//System.out.println(i++);
fos.write(bs, 0, n);
}
fos.flush();
fos.close();
is.close();
String serpath = req.getContextPath();
String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
+ serpath + "/";
System.out.println(item.getContentType());
//这里为我测试添加的用于将添加的图片加载出来
//没什么用
if (item.getContentType().equals("image/jpeg")) {
out.write("<img src=\""+basePath+
"OutFile.do?type="+item.getContentType()+"&name="+item.getName()+"\"/>");
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
out.write("传输成功");
out.write("</body>");
out.write("</html>");
out.flush();
out.close();
}
}
用于存放进度信息的Java been
`package com.whbweb.top.pojo;
public class UploadStatus {
//参数含义在html中有说明
private long bytesRead;
private long contentLength;
private int items;
private long startTime=System.currentTimeMillis();
public long getBytesRead() {
return bytesRead;
}
public void setBytesRead(long bytesRead) {
this.bytesRead = bytesRead;
}
public long getContentLength() {
return contentLength;
}
public void setContentLength(long contentLength) {
this.contentLength = contentLength;
}
public int getItems() {
return items;
}
public void setItems(int items) {
this.items = items;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
}
`
实现进度监听器
package com.whbweb.top.util;
import org.apache.commons.fileupload.ProgressListener;
import com.whbweb.top.pojo.UploadStatus;
/*
* 精度监听函数,需要实现update
* 用于跟新status参数
* 原理:在构造函数时,会自动将session中的session放入,每次调用update时只需要重新赋值即可
*
* */
public class UploadListener implements ProgressListener{
private UploadStatus status;
public UploadListener(UploadStatus status) {
this.status=status;
}
@Override
public void update(long bytesRead, long contentLength, int items) {
// TODO Auto-generated method stub
status.setBytesRead(bytesRead);
status.setContentLength(contentLength);
status.setItems(items);
}
}
获取进度信息的servlet
package com.whbweb.top.servlet;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.whbweb.top.pojo.UploadStatus;
import com.whbweb.top.util.JsonUtil;
@WebServlet(urlPatterns="/UpFileSup.do")
public class UpFileSup extends HttpServlet{
/**
* 用于输出传输文件时的进度参数
* 进度信息保存在session域中,具体名称在com.whbweb.top.servlet.UpFileServlet.java中查看
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {//这里睡眠是为了防止客户端过快的去调用跟新参数,造成资源浪费,需要细腻的跟新进度条时只需要降低时间即可
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//从session域中获取进度信息
UploadStatus status=(UploadStatus) req.getSession().getAttribute("status");
String json=JsonUtil.transToJsonStr(status);
System.out.println(json);
JsonUtil.outJsonStrAndColse(resp, json);
}
}
其他工具类
package com.whbweb.top.util;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtil {
public static String transToJsonStr(Object obj){
ObjectMapper mapper = new ObjectMapper();
//mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
StringWriter sw = new StringWriter();
String strJson = null ;
try {
mapper.writeValue(sw, obj);
strJson = sw.toString();
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return strJson ;
}
public static void outJsonStrAndColse(HttpServletResponse resp,String jsonStr){
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
PrintWriter out;
try {
out = resp.getWriter();
out.write(jsonStr);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}