@MultiPartConfig 实际上只是容器的标记接口。当 servlet 初始化时,提供的注释值通过代理对象映射到它。当传入的请求是 multipart/form-data 时,上传的部分将映射到请求,并且容器根据注释中的值和请求中的部分执行必要的工作。您无法拦截此过程,因为这一切都发生在容器的内部。但是,还有一种选择。它需要第二次执行文件系统操作。由于您拥有所有部分,因此您可以重建文件并将其“重新上传”到您选择的位置。它可能看起来像下面的方法。
@Override
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
httpServletResponse.setContentType("text/html");
PrintWriter printWriter = httpServletResponse.getWriter();
InputStream inputStream;
FileOutputStream fileOutputStream;
for (Part part : httpServletRequest.getParts()) {
inputStream = httpServletRequest.getPart(part.getName()).getInputStream();
int i = inputStream.available();
byte[] b = new byte[i];
inputStream.read(b);
String fileName = "";
for (String temp : part.getHeader("content-disposition").split(";")) {
if (temp.trim().startsWith("filename")) {
fileName = temp.substring(temp.indexOf('=') + 1).trim().replace("\"", "");
}
}
String uploadDir = "/temp";
fileOutputStream = new FileOutputStream(uploadDir + "/" + fileName);
fileOutputStream.write(b);
inputStream.close();
fileOutputStream.close();
printWriter.write("Uploaded file " + uploadDir + "/" + fileName + ".");
}
}