spring mvc为multipart/form-data添加JSON消息转换器

在SpringMVC应用中,尝试接收包含文件和JSON元数据的多部分请求时遇到转化异常。使用`@RequestParam`注解处理JSON时,需要将`@RequestParam`改为`@RequestPart`,以便让Spring使用消息转换器正确处理JSON对象。这样可以避免ConversionNotSupportedException,允许服务器端正确解析MyClass类型的参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在我的Spring MVC服务器中,我想要接收包含文件(图像)和一些JSON元数据的multipart / form-data请求。 我可以在JSON部分具有Content-Type=application/json的情况下构建格式良好的多部分请求。
Spring服务的形式如下:

@RequestMapping(value = MY_URL, method=RequestMethod.POST, headers="Content-Type=multipart/form-data")
public void myMethod(@RequestParam("image") MultipartFile file, @RequestParam("json") MyClass myClass) {
...
}

该文件已正确上传,但我遇到了JSON部分的问题。我得到这个错误:

``
org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type ‘java.lang.String’ to required type ‘myPackage.MyClass’; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [myPackage.MyClass]: no matching editors or conversion strategy found

如果我不使用多部分请求JSON转换可以很好地使用Jackson 2,但是当使用多部分时,我会得到以前的错误。我想我必须配置多部分消息转换器来支持JSON作为消息的一部分,但我不知道如何。这是我的配置:

mvc:annotation-driven
mvc:message-converters

</mvc:message-converters>
</mvc:annotation-driven>
如果我使用String作为myClass的类型而不是MyClass,但是我希望使用Spring MVC支持进行参数转换,所有这些都可以很好地工作。

如果您使用@RequestPart注释而不是@RequestParam,它实际上将通过消息转换器传递参数。 因此,如果您将控制器方法更改为以下内容,它应该如您所述:

@RequestMapping(value = MY_URL, method=RequestMethod.POST, headers="Content-Type=multipart/form-data")
public void myMethod(@RequestParam("image") MultipartFile file, @RequestPart("json") MyClass myClass) {
...
}

您可以在Spring参考指南中阅读更多相关信息:http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/mvc.html#mvc-multipart-forms-non-browsers

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值