标签:res type multipart over repos web gre adt family
自从业至今,文件上传与IO流之类的调用,一直是理解比较模糊的地方,大多就这网上搜到的资料抄抄改改草草了事,内部原理一直不甚了解,今日我们通过Spring的CommonsMultipartResolver的工具类一探文件上传的秘密;
1.首先我们先看看CommonsMultipartResolver本身:
截图为CommonsMultipartResolver类的继承及接口实现关系:
a)我们首先看看感觉最没有关系的ServletContextAware,CommonsMultipartResolver实现了setServletContext方法,当没有指定临时的上传路径时,将上传的文件保存到ServletContext默认的位置;
@Override public void setServletContext(ServletContext servletContext) { if (!isUploadTempDirSpecified()) { getFileItemFactory().setRepository(WebUtils.getTempDir(servletContext)); } }
b)我们再来看看MultipartResolver接口:
CommonsMultipartResolver实现了截图中的三个方法,三个方法的源代码可以自己去查看,简单的说下方法的功能:
resolveMultipart将HttpServletRequest转化为MultipartHttpServletRequest,将里面的FileItem不是表单字段的对象转换为MultipartFile;
@Override public MultipartHttpServletRequest resolveMultipart(final HttpServletRequest request) throws MultipartException { Assert.notNull(request, "Request must not be null"); if (this.resolveLazily) { return new DefaultMultipartHttpServletRequest(request) { @Override protected void initializeMultipart() { MultipartParsingResult parsingResult = parseRequest(request); setMultipartFiles(parsingResult.getMultipartFiles()); setMultipartParameters(parsingResult.getMultipartParameters()); setMultipartParameterContentTypes(parsingResult.getMultipartParameterContentTypes()); } }; } else { MultipartParsingResult parsingResult = parseRequest(request); return new DefaultMultipartHttpServletRequest(request, parsingResult.getMultipartFiles(), parsingResult.getMultipartParameters(), parsingResult.getMultipartParameterContentTypes()); } }
isMultipart(HttpServletRequest request)判断HttpServletRequest请求方式是否为post方式,content-type中是否以multipart/开头;
cleanupMultipart(MultipartHttpServletRequest request)将请求中的FileItem删除;
c)最后来看看抽象类CommonsFileUploadSupport,我们比较常用的是MultipartParsingResult parseRequest(HttpServletRequest request)这个方法。
2.CommonsMultipartResolver过程中涉及到的类:
3.Spring文件上传的过程总结:
Spring CommonsMultipartResolver上传文件小结
标签:res type multipart over repos web gre adt family
原文地址:http://www.cnblogs.com/angry-scholar/p/7742601.html