文件上传

最后发布时间:2022-01-06 13:07:30 浏览量:

firefox

图片alt

图片alt

图片alt

图片alt

chrome

图片alt

图片alt

一个正确的例子

图片alt

图片alt

  • DispatcherServlet是SpringMVC中的前端控制器(front controller),负责接收request并将request转发给对应的处理组件

  • HanlerMapping是SpringMVC中完成url到Controller映射的组件。DispatcherServlet接收request,然后从HandlerMapping查找处理request的controller.

  • Cntroller处理request,并返回ModelAndView对象,Controller是SpringMVC中负责处理request的组件(类似于struts2中的Action),ModelAndView是封装结果视图的组件。

  • 视图解析器解析ModelAndView对象并返回对应的视图给客户端。
    https://blog.csdn.net/win7system/article/details/90674757

  • DispatcherServlet#doDispatch

  • RequestMappingHandlerAdapter#invokeHandlerMethod

DispatcherServlet.java
protected void initStrategies(ApplicationContext context) {
		initMultipartResolver(context);
		.....
}
private void initMultipartResolver(ApplicationContext context) {
		try {
			//从Spring的上下文中获取id为multipartResolver的bean作为它的MutipartResolver
			this.multipartResolver = context.getBean(`multipartResolver`, MultipartResolver.class);
			if (logger.isTraceEnabled()) {
				logger.trace("Detected " + this.multipartResolver);
			}
			else if (logger.isDebugEnabled()) {
				logger.debug("Detected " + this.multipartResolver.getClass().getSimpleName());
			}
		}
		catch (NoSuchBeanDefinitionException ex) {
			// Default is no multipart resolver.
			this.multipartResolver = null;
			if (logger.isTraceEnabled()) {
				logger.trace("No MultipartResolver '" + MULTIPART_RESOLVER_BEAN_NAME + "' declared");
			}
		}
	}

待看源码

  • 如果有@RequestPart则request必须是multpart/form-data
  • 如果@RequestPart(required = false)或没有@RequestPart可以使用传统的请求,也可以使用multpart/form-data,只是使用multpart/form-data可以上传文件
  • 在RequestMappingHandlerAdapter#invokeHandlerMethod统一处理
    @PostMapping(value = "/testUpload")
    public Attachment testUpload(String name, @RequestPart(required = false)MultipartFile file2){
        if(file2!=null){
            return  attachmentService.upload(file2);
        }
        return new Attachment();
    }

https://github.com/wangyang1749/shope_base_servlert/blob/master/src/com/shop/servlet/MultipartRequestWrapper.java

springmvc多文件上传

 <form action="http://localhost:8080/api/template/upload" method="post"  enctype="multipart/form-data">  
        <p>选择文件:<input type="file" name="file"></p>
        <p>选择文件:<input type="file" name="file"></p>
        <p><input type="submit" value="提交"></p>
    </form>  
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Anonymous
    public Attachment upload(@RequestPart("file") MultipartFile[] file){
        return  null;
    }

参考:
https://blog.csdn.net/suifeng3051/article/details/51659731
https://blog.csdn.net/suifeng3051/article/details/51659731