需求很简单,就是希望 上传文件的大小超过限制后跳转到另一个页面给出提示
代码如下,文件大小不超过限制时没有问题可以跳转到提示页面,但是一旦超过大小(即抛出异常),页面就显示 “ 连接被重置 ”。
@WebServlet(urlPatterns = { "/upfile" })
public class MyServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(1024 * 1024 * 5); // 设置单次上传大小最大值5M
try {
//省略获取上传文件代码。。。
//【成功时可以跳转】
resp.sendRedirect(req.getContextPath()+"/index.jsp?msg=ok");
} catch (FileUploadException e) {
//【失败时无法跳转,且页面显示 连接被重置】
resp.sendRedirect(req.getContextPath()+"/index.jsp?msg=error");
}
}
}