1. Describe
I used springboot to integrate swagger, and upload files at the same time. The code is as follows ( code function is fine, it has been tested ):
//
@Api(value = "", description = "API")
@RestController
public class UploadController {
@Autowired
private FileUploadService fileUploadService;
@ApiOperation(value = "", notes = "")
@RequestMapping(value = "/api/upload", method = RequestMethod.POST, consumes = "multipart/form-data")
public RestResult upload(@RequestParam MultipartFile file) {
String fileFullPath = fileUploadService.upload(file);
return RestResultGenerator.getSuccessResult(fileFullPath);
}
}
//swagger2
@ConditionalOnProperty(prefix = "swagger2", value = {"enable"}, havingValue = "1")
@EnableSwagger2
@Configuration
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.freedom.clothing.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Restful API")
.contact(new Contact("xx", "", ""))
.version("1.0")
.description("")
.build();
}
}
//DisPatcherServlet
@Configuration
@EnableWebMvc//(swagger2)
public class WebMVCConfig extends WebMvcConfigurerAdapter {
@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
resolver.setMaxInMemorySize(40960);
resolver.setMaxUploadSize(10485760);
return resolver;
}
}
2. The problem I encountered
1 but when I turned on the @ EnableWebMvc annotation, the file could be uploaded, but swagger2 could not access .
@EnableWebMvcswagger2uploadorg.springframework.web.HttpMediaTypeNotSupportedException
3. The question I want to ask
it took me a long time to figure out why, and I always thought there was something wrong with the upload.
my thinking: when @ EnableWebMvc is added to
, it is obvious that the static resources of swagger are blocked, and if you do not add @ EnableWebMvc, you will not intercept.
1 is not all set DispatcherServlet, and the mapping mapping of the two cases is different?
what exactly does 2@EnableWebMvc do? Why sometimes it doesn"t seem to matter whether you add it or not (it should have nothing to do with springboot"s @ EnableAutoConfiguration, I didn"t open this comment).