java - 将@RequestParam 用于多部分文件是正确的方法吗?

标签 java spring spring-mvc spring-boot multipart

我正在开发一个 spring mvc 应用程序,我想在我的 Controller 中处理多部分请求。在请求中我也传递了 MultiPartFile,目前我正在使用 @RequestParam 来获取文件参数,方法看起来像,

@RequestMapping(method = RequestMethod.POST)
public def save(
        @ModelAttribute @Valid Product product,
        @RequestParam(value = "image", required = false) MultipartFile file) {
    .....
}

以上代码在我的服务中运行良好,并且文件正在服务器端。现在我在某个地方看到,如果该文件需要使用 @RequestPart 注释而不是 @RequestParam。将 @RequestParam 用于文件有什么问题吗?或者将来可能会导致任何类型的错误?

最佳答案

使用 @RequestParamMultipart 文件没有问题。

@RequestParam annotation can also be used to associate the part of a "multipart/form-data" request with a method argument supporting the same method argument types. The main difference is that when the method argument is not a String, @RequestParam relies on type conversion via a registered Converter or PropertyEditor while @RequestPart relies on HttpMessageConverters taking into consideration the 'Content-Type' header of the request part. @RequestParam is likely to be used with name-value form fields while @RequestPart is likely to be used with parts containing more complex content (e.g. JSON, XML).

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestPart.html

关于java - 将@RequestParam 用于多部分文件是正确的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38156646/

相关文章:

java - 图像图标未显示在 JButton 上

web-services - spring web services - 如何在方法端点中获取字符串有效负载?

java - ANTLR4 运行时 JAR

java - 使用两个 TextView 将过滤器添加到 ListView

java - JdbcSQLException 超过 40 次测试

java.lang.NoSuchMethodError : org. springframework.util.ReflectionUtils.accessibleConstructor

java - 在 Spring MVC 上将 JSONObject 作为参数传递

spring - <context :component-scan. ../> 和 <context :property-placeholder. ../> 在分层上下文中的范围

Spring MVC : Can not deserialize instance of out of START_ARRAY token

java - java中不同长度的数组的数组