问题:

@PostMapping(value = "/test")
public Result<Test> test(@RequestPart("file") MultipartFile multipartFile,
                                          @RequestPart("test") String test,
                                          HttpServletRequest request)

 当test 参数给中文时,获取到的值是乱码的

原因:

 @RequestPart注解由RequestPartMethodArgumentResolver进行解析

当参数是string时,会由readWithMessageConverters方法解析参数,并从body中获取值

解决 @RequestPart注解 参数中文乱码问题

 

由于参数是string类型的,就会使用StringHttpMessageConverter进行解析,也就其readInternal方法

解决 @RequestPart注解 参数中文乱码问题

问题就出在getContentTypeCharset方法中

解决 @RequestPart注解 参数中文乱码问题

由于contentType为空,此时会走getDefaultCharset,而其默认的charset为ISO_8859_1

解决 @RequestPart注解 参数中文乱码问题

问题就出在这里,我们需要修改为UTF-8

 

解决:实现WebMvcConfigurer接口,并实现extendMessageConverters方法,修改

StringHttpMessageConverter的defaultCharset为UTF-8 即可

解决 @RequestPart注解 参数中文乱码问题

 这样处理后,后面只要是用了StringHttpMessageConverter解析的中文就不会有乱码

相关文章:

  • 2021-05-18
  • 2022-12-23
  • 2021-12-23
  • 2022-12-23
  • 2021-10-09
  • 2021-05-27
猜你喜欢
  • 2021-08-10
  • 2022-12-23
  • 2022-12-23
  • 2021-12-29
相关资源
相似解决方案