我有一个 servlet,用于许多不同的操作,用于 前控制器模式. 。有谁知道是否可以判断发回的数据是否为 ​​enctype="multipart/form-data"?在我决定之前,我无法读取请求参数,因此我无法将请求分派到正确的控制器。

有任何想法吗?

有帮助吗?

解决方案

是的 Content-type 用户代理请求中的标头应包含 multipart/form-data (至少)HTML4 规范中描述的:

http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

其他提示

如果您打算尝试使用上面提供的 request.getContentType() 方法,请注意:

  1. request.getContentType() 可能返回 null。
  2. request.getContentType() 可能不是 平等的 到“multipart/form-data”,但可能只是从它开始。

考虑到这一点,您应该运行的检查是:

if (request.getContentType() != null && request.getContentType().toLowerCase().indexOf("multipart/form-data") > -1 ) {
// Multipart logic here
}

您可以调用方法来获取内容类型。

http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletRequest.html#getContentType()

根据 http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2, ,内容类型将为“multipart/form-data”。

不要忘记:

  1. request.getContentType() 可能返回 null。

  2. request.getContentType() 可能不等于“multipart/form-data”,但可能只是从它开始。

因此,考虑到这一切:

if (request.getContentType() != null && 
    request.getContentType().toLowerCase().indexOf("multipart/form-data") > -1 ) 
{
    << code block >>
} 

ServletFileUpload 实现 isMultipartContent()。也许您可以根据您的需要提升此实现(而不是通过开销来创建 ServletFileUpload)。

http://www.docjar.com/html/api/org/apache/commons/fileupload/servlet/ServletFileUpload.java.html

您必须阅读请求参数才能确定这一点,至少在 一些 等级。ServletRequest 类有一个您需要查看的 getContentType 方法。

扩展至 awm129 的回答 - Apache commons 的实现与此相对应:

if (request != null 
        && request.getContentType() != null 
        && request.getContentType().toLowerCase(Locale.ENGLISH).startsWith("multipart/")) {
    ...
}

您可以使用 Apache commons 将其写得更短 org.apache.commons.lang3.StringUtils:

if (StringUtils.startsWithIgnoreCase(request.getContentType(), "multipart/")) { 
    ... 
}

https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getParts()

java.util.Collection getParts()

投掷:ServletException - 如果此请求不是 multipart/form-data 类型

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top