I am trying to use Java Servlet 3.0 to upload files.
@WebServlet("/uploadFile")
@MultipartConfig(fileSizeThreshold=1024*1024*1,
maxFileSize=1024*1024*10,
maxRequestSize=1024*1024*100)
public class FileUploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String serverUploadDir = getServerUploadDir(req);
Part file;
try {
file = req.getPart("fileName");
file.write(serverUploadDir + File.separator + file.getSubmittedFileName());
res.sendRedirect("viewDirectory?msg=File Uploaded.");
}
catch (IllegalStateException ex) {
System.out.println(ex.getMessage());
}
}
public String getServerUploadDir(HttpServletRequest req) {
return req.getParameter("serverUploadDir");
}
}
It works correctly when files are under maxFileSizedeclared in @MultipartConfig annotation. However, when they exceed this size, I get an IllegalStateException and my browser says Connection was Reset. Even if I try to redirect the request to another page in catch, this will not work.
I know using the Spring framework, I can create filterMultipartResolver, and this will allow me to handle when exceeded maxUploadSize. Is there a way to create a regular Java servlet filter to do the same?
source
share