为什么不能从java中的RequestBody获取文件数据? [英] Why cant we get a file data from a RequestBody in java?

查看:6653
本文介绍了为什么不能从java中的RequestBody获取文件数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图上传一个文件到服务器,所以我想使用@RequestBody来获取文件的数据,但是当我尝试上传文件的时候,我得到了415错误代码。



所以我google了(得到解决方案上传文件),并得知我不能从请求正文获取文件数据。所以我想知道为什么我们不能从请求主体访问文件数据,因为数据将在HTTP请求中的请求正文中发送,所以我想知道如何在上传文件的情况下发生请求。



我之前的服务器代码:

  @RequestMapping(value =/ upload,headers = Content-Type = multipart / form-data,method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestBody MultipartFile file)
{
}

解决方案:

 <$ c $ ()方法,请求方法,请求方法,请求方法,请求方法,请求方法,请求方法,请求方法,请求方法b $ b {
}


解决方案

可以编写自己的 HttpMessageConverter ,它将解析完整的多部分请求主体,但是必须有一个特定的目标类型来处理所有的部分。



您会从javadoc注意到 @RequestBody


表示方法参数的Annotation应绑定到Web请求的正文


意图是将整个请求主体绑定到方法参数。如何将多部分请求的每个部分绑定到单个参数?类似于 MultiValueMap< String,Object> 这就是写入多部分请求时 FormHttpMessageConverter 一>)。但是这不会很有用,因为你必须检查每个值的类型。

作为一名开发人员,更确切地说明您需要什么。这就是为什么 @RequestParam @RequestPart 可用。


I am trying to upload a file to a server so i am trying to use @RequestBody to get the data of the file, but i am getting 415 error code while trying to upload a file.

So i have googled(got solution to upload a file) and got to know that i cant get file data from a request body. So i want to know why cant we access file data from request body as data will be sent in request body in HTTP requests, so i want to know how is the request happening in the case of uploading a file.

My server code before:

@RequestMapping(value = "/upload",headers = "Content-Type=multipart/form-data", method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestBody MultipartFile file)
{
}

Solution:

@RequestMapping(value = "/upload",headers = "Content-Type=multipart/form-data", method = RequestMethod.POST)
@ResponseBody
public String upload(MultipartHttpServletRequest request)
{
}

解决方案

Technically you could write your own HttpMessageConverter which would parse the full multipart request body, but you'd have to have a very specific target type that could handle all the parts.

You'll notice from the javadoc of @RequestBody

Annotation indicating a method parameter should be bound to the body of the web request.

that the intention is to bind the entirety of the request body to the method parameter. How do you bind every part of a multipart request to a single parameter? Something like a MultiValueMap<String, Object> (which is what FormHttpMessageConverter uses when writing a multipart request). But that wouldn't be very useful because you'd have to check the type of each value.

It makes much more sense as a developer to specify exactly what you need. That's why @RequestParam and @RequestPart are available.

这篇关于为什么不能从java中的RequestBody获取文件数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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