对 multipartfile 使用 @RequestParam 是正确的方法吗? [英] Using @RequestParam for multipartfile is a right way?

查看:294
本文介绍了对 multipartfile 使用 @RequestParam 是正确的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm developing a spring mvc application and I want to handle multipart request in my controller. In the request I'm passing MultiPartFile also, currently I'm using @RequestParam to get the file parameter, the method look like,

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

以上代码在我的服务中运行良好,文件正在服务器端获取.现在在某处我看到在文件需要使用 @RequestPart 注释而不是 @RequestParam 的情况下.将 @RequestParam 用于文件有什么问题吗?或者将来可能会导致任何类型的错误?

Above code works well in my service and the file is getting on the server side. Now somewhere I saw that in cases that file need to use @RequestPart annotation instead of @RequestParam. Is there anything wrong to use @RequestParam for file ? Or it may cause any kind of error in future?

推荐答案

使用 @RequestParamMultipart 文件没有错.

It is nothing wrong using @RequestParam with Multipart file.

@RequestParam 注解也可以用来关联一个multipart/form-data" 请求,方法参数支持相同的方法参数类型.主要区别在于,当方法参数不是字符串,@RequestParam 依赖于类型通过注册的 Converter 或 PropertyEditor 进行转换,同时考虑到@RequestPart 依赖于 HttpMessageConverters请求部分的Content-Type"标头.@RequestParam 很可能与名称-值表单字段一起使用,而@RequestPart 可能与包含更复杂内容的部分(例如 JSON、XML)一起使用.

@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

这篇关于对 multipartfile 使用 @RequestParam 是正确的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆