在servlet中配置 multipart-config
,规定multipart/form-data post请求的大小限制。
各字段含义如下:
location
:硬盘临时存储文件的地方。默认为空,用的是context默认的临时文件夹CATALINA_BASE/work/engine/host/context文件夹
max-file-size
:单个文件的最大字节数。默认为-1,即无限制。
max-request-size
:单个request最大的字节数。默认为-1,即无限制。
file-size-threshold
:文件超过该阈值就会被存到硬盘中,否则存在内存里。默认为0,即直接存在硬盘里。
必须配 !!否则会报Unable to process parts as no multi-part configuration has been provided错误。
web.xml配置方法
<servlet>
<multipart-config>
<location></location>
<max-file-size>-1</max-file-size>
<max-request-size>-1</max-request-size>
<file-size-threshold>0</file-size-threshold>
</multipart-config>
</servlet>
注解配置方法
@MultipartConfig
public class UploadPhotoServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Collection<Part> parts = request.getParts();
System.out.println(parts.size());
for (Part part : parts) {
System.out.println(part.getName());
}
}
}
两者选一,web.xml配了的话,注解的就不生效了。
maxPostSize
网上很多提到的Connector中的参数maxPostSize,在当前版本中,它不限制文件大小。
它的两个主要作用:
- 限制content-type为
application/x-www-form-urlencoded
的post 请求体的大小。 - 限制content-type为
multipart/form-data
时,请求体中所有非文件部分总和的大小。默认2M。设成-1表示无限制。
文档中该字段的含义The maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The limit can be disabled by setting this attribute to a value less than zero. If not specified, this attribute is set to 2097152 (2 megabytes)
这是解析参数源码部分(简化后)
// org/apache/catalina/connector/Request.java # parseParameters
// 解析url中的参数
parameters.handleQueryParameters();
// 不是POST方法就结束,不用解析请求体
if( !getConnector().isParseBodyMethod(getMethod()) ) {
success = true;
return;
}
String contentType = getContentType();
// 解析multipart/form-data的请求体,parseParts的解析在本文后面。
if ("multipart/form-data".equals(contentType)) {
parseParts(false);
success = true;
return;
}
// 当content-type为application/x-www-form-urlencoded才会继续往后执行
if (!("application/x-www-form-urlencoded".equals(contentType))) {
success = true;
return;
}
int len = getContentLength();
if (len > 0) {
// maxPostSize出现了!!
int maxPostSize = connector.getMaxPostSize();
if ((maxPostSize > 0) && (len > maxPostSize)) {
Context context = getContext();
if (context != null && context.getLogger().isDebugEnabled()) {
context.getLogger().debug(
sm.getString("coyoteRequest.postTooLarge"));
}
checkSwallowInput();
return;
}
// 解析请求体
parameters.processParameters(formData, 0, len);}
}
解析multipart/form-data请求体的源码
调用request.getParts()就可以得到multipart/form-data中的每个part,包括文件和普通的键值对。
// org/apache/catalina/connector/Request.java
@Override
public Collection<Part> getParts() throws IOException, IllegalStateException,
ServletException {
// 从请求体中解析parts
parseParts(true);
// ...
return parts;
}
private void parseParts(boolean explicit) {
// Return immediately if the parts have already been parsed
if (parts != null || partsParseException != null) {
return;
}
Context context = getContext
// 获取在servlet中配置的multipart-config
MultipartConfigElement mce = getWrapper().getMultipartConfigElement();
// explicit为true的前提下,如果没有配multipart-config就报错
if (mce == null) {
//抛异常
}
Parameters parameters = coyoteRequest.getParameters();
parameters.setLimit(getConnector().getMaxParameterCount());
boolean success = false;
try {
// 获取硬盘临时存储位置location
File location;
String locationStr = mce.getLocation();
if (locationStr == null || locationStr.length() == 0) {
location = ((File) context.getServletContext().getAttribute(
ServletContext.TEMPDIR));
} else {
// If relative, it is relative to TEMPDIR
location = new File(locationStr);
if (!location.isAbsolute()) {
location = new File(
(File) context.getServletContext().getAttribute(
ServletContext.TEMPDIR),
locationStr).getAbsoluteFile();
}
}
if (!location.isDirectory()) {
partsParseException = new IOException(
sm.getString("coyoteRequest.uploadLocationInvalid",
location));
return;
}
// 创建一个用于创建DiskFileItem的工厂,DiskFileItem表示可以存储在硬盘或者内存中的一个part
// 它会根据multipart-config中设置的阈值决定把part存到硬盘还是内存中。
// Create a new file upload handler
DiskFileItemFactory factory = new DiskFileItemFactory();
try {
factory.setRepository(location.getCanonicalFile());
} catch (IOException ioe) {
partsParseException = ioe;
return;
}
factory.setSizeThreshold(mce.getFileSizeThreshold());
// 创建解析器
ServletFileUpload upload = new ServletFileUpload();
upload.setFileItemFactory(factory);
upload.setFileSizeMax(mce.getMaxFileSize());
upload.setSizeMax(mce.getMaxRequestSize());
parts = new ArrayList<>();
try {
// 开始解析
List<FileItem> items =
upload.parseRequest(new ServletRequestContext(this));
// ... 省略编码转换部分.
// 把解析结果都放到parts里面
for (FileItem item : items) {
ApplicationPart part = new ApplicationPart(item, location);
parts.add(part);
if (part.getSubmittedFileName() == null) {
// 把不是file的part 当作parameter放进parameterMap,涉及到maxPostSize检查
}
}
success = true;
} catch (//...)
{
//... 省略catch部分
}
} finally {
if (partsParseException != null || !success) {
parameters.setParseFailed(true);
}
}
}