JavaEE拾遗01--异步上传文件

时间:2022-04-17 23:43:53

今天学习了JavaEE的Servlet的异步调用和文件上传,合着做了一个异步上传文件练习,注意到Servlet是多线程的,所以实际操作中不需要异步操作(我是这么觉得的),闲话少说,看代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<form method="post" action="../upload" enctype="multipart/form-data">
文件名:<input type="text" id="name" name="name" /><br />
选择上传文件:<input type="file" id="file" name="file" />
<input type="submit" value="上传" />
</form>
</body>
</html>

上面写了一个jsp页面,这个页面的<input type="file" /><form method="post" action="../upload" enctype="multipart/form-data">是可以实现文件上传的秘密

接下来是处理文件上传的servlet

package liujie.jee.uploadfile;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import liujie.jee.bean.UploadFileExecutor;

//使用注解表示这个servlet支持异步操作,
@WebServlet(urlPatterns = { "/upload" }, name = "upload", asyncSupported = true)
// 处理文件上传的servlet需要使用MultipartConfig标识
@MultipartConfig
public class UploadFileServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
// 得到文件名
String fileName = request.getParameter("name");
out.println("开始上传文件:" + fileName + ".</br>");
// 示例化异步调用
AsyncContext asct = request.startAsync();
// 设置任务超时时间为10分钟
asct.setTimeout(10 * 60 * 1000);
// 设置异步调用的监听器,当调用完成时提示
asct.addListener(new AsyncListener() {

// 出错时调用
@Override
public void onError(AsyncEvent event) {
}

// 完成时调用
@Override
public void onComplete(AsyncEvent event) {
out.println("文件:" + fileName + "上传完毕");
}

// 开始时调用
@Override
public void onStartAsync(AsyncEvent event) {
}

// 超时时调用
@Override
public void onTimeout(AsyncEvent event) {
}
});
asct.start(new UploadFileExecutor(asct));
/*
* out.println("文件大小为:" + fileSize + "</br>"); out.println("上传文件的类型是:" +
* part.getContentType() + ".</br>"); out.println("文件名为:" + filename +
* "</br>");
*/

}
}

注释比较详细,就不仔细介绍了

里面的异步任务实际上是启动了一个runnable对象,接下来是这个类的内容

package liujie.jee.bean;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

public class UploadFileExecutor implements Runnable {
private AsyncContext asct;
private Part part;
private final static String UPLODA_DIR = "z_uploadfiles";

public UploadFileExecutor(AsyncContext asct) {
this.asct = asct;
}

@Override
public void run() {
HttpServletRequest request = (HttpServletRequest) asct.getRequest();
String fileName = request.getParameter("name");
try {
// 获取上传的对象
Part part = request.getPart("file");
// 获取保存的路径并将文件吸入改路径
part.write(request.getServletContext().getRealPath(UPLODA_DIR)
+ "\\" + fileName);
// 完成调用
asct.complete();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

注意要在应用根目录下面建立一个z_uploadfiles的目录放文件