我想检测Http-Request是否是文件上传。我知道,有一些视图可能表明文件上传:
有一个观点问题:
如何区分文件上传和普通的html格式帖子?浏览器是否使用chunked-encoding进行文件上传? (据我所知,这将是毫无意义的,但我不知道很多)
答案 0 :(得分:1)
通常可以通过检查请求是否为 multipart 来检测。
以下示例代码是来自Apache Commons FileUpload库(http://javasourcecode.org/html/open-source/commons-fileupload/commons-fileupload-1.2.2/org/apache/commons/fileupload/servlet/ServletFileUpload.java.html)的c& p
/**
* Utility method that determines whether the request contains multipart
* content.
*
* @param request The servlet request to be evaluated. Must be non-null.
*
* @return <code>true</code> if the request is multipart;
* <code>false</code> otherwise.
*/
public static final boolean isMultipartContent(
HttpServletRequest request) {
if (!"post".equals(request.getMethod().toLowerCase())) {
return false;
}
String contentType = request.getContentType();
if (contentType == null) {
return false;
}
if (contentType.toLowerCase().startsWith(MULTIPART)) {
return true;
}
return false;
}
其中MULTIPART是
/**
* Part of HTTP content type header.
*/
public static final String MULTIPART = "multipart/";
答案 1 :(得分:0)
检查多部分表单提交只会让您通过前门。问题是,您可以进行实际上不包含文件上载的多部分表单提交。如果您想知道您是否确实有上传的文件,则需要搜索表单部分。像这样:
public static int getUploadCount(HttpServletRequest request) throws Exception{
int fileCt = 0;
String[] tokens;
String contentDisp;
String fileName;
//Search through the parts for uploaded files
try{
for (Part part : request.getParts()) {
fileName = "";
contentDisp = part.getHeader("content-disposition");
//System.out.println("content-disposition header= "+contentDisp);
tokens = contentDisp.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
fileName = token.substring(token.indexOf("=") + 2, token.length()-1);
}
}
if(!fileName.equals("")){
fileCt++;
}
}
}catch(ServletException ex){
throw new Exception(ex);
}
return fileCt;
}