Spring Boot @RequestPart 字符集编码

编程入门 行业动态 更新时间:2024-10-28 19:32:17
本文介绍了Spring Boot @RequestPart 字符集编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个端点,它 consumes = MediaType.MULTIPART_FORM_DATA_VALUE,使用 POST 方法产生 = MediaType.APPLICATION_JSON_VALUE.

I have an endpoint which consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE with POST method.

有 2 个参数 @RequestPart(name = "model", required = true) String jsonPart, @RequestPart(name = "images", required = false) MultipartFile[] images.第一个参数是一个 JSON 字符串,稍后我将使用 ObjectMapper 解析成一个 POJO多部分[].唯一的问题是初始 JSON 字符串中的 name 值没有采用正确的编码.

There are 2 arguments @RequestPart(name = "model", required = true) String jsonPart, @RequestPart(name = "images", required = false) MultipartFile[] images. The first argument is a JSON string which I'll use the ObjectMapper to parse into a POJO later which goes well and also the receive of the Multipart[]. Only problem is that the name value in the initial JSON string was not in the right encoding.

这是来自 multipart-form/data request 的 JSON 字符串,它被正确解析,这里我给它值 White Lé FrÖÖnt

This is the JSON string from the multipart-form/data request which was properly parsed, here I'm giving it the value White Lé FrÖÖnt

这是 @RequestPart 中调试后的 JSON 字符串,给出了出乎意料的 White LeÌ FrÃnt

This is the debugged JSON string in the @RequestPart giving White LeÌ FrÃnt which was not expected

以下是我迄今为止从浏览网页中收集的建议

Here are the suggestions that I've tried so far collected from browsing through the web

  • 将 CharacterEncodingFilter 添加到 Spring Security FilterChain 中,尽可能优先
  • server.servlet.encoding.enabled=true 和 server.servlet.encoding.force=true 甚至 server.servlet.encoding.force=false 在 application.properties 中
  • Adding CharacterEncodingFilter into Spring Security FilterChain as prioritized as possible
  • server.servlet.encoding.enabled=true and server.servlet.encoding.force=true or even server.servlet.encoding.force=false in application.properties
  • 其中没有一个单独工作或一起工作.我的想法是 request 没有任何问题,而是我需要添加到服务器才能使其工作的东西.感谢您抽出宝贵时间,感谢您的帮助.

    None of which work individually or collectively together. What I have in mind is that there's nothing wrong with the request but rather something that I need to add to the server in order for it to work. Thanks for your time, I appreciate any help.

    推荐答案

    解决该问题的一种方法是将参数类型设置为 MultipartFile

    An approach to solve the issue could be to set the parameter type to MultipartFile

    @RequestPart(name = "model", required = true) MultipartFile model

    然后使用 model.getBytes() 获取内容并将其传递给 ObjectMapper.

    Then get contents with model.getBytes() and pass that to ObjectMapper.

    更多推荐

    Spring Boot @RequestPart 字符集编码

    本文发布于:2023-11-09 19:32:21,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1573235.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:字符集   Spring   Boot   RequestPart

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!