弹簧启动支架控制器不接受多部分表格数据

时间:2020-07-02 05:12:42

标签: spring spring-boot http

我想将多部分表单数据发送到我的Spring Boot Rest Controller。

下面是我的请求处理程序代码

@PostMapping(value = "/postmultipartformdata" , consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String postFormData(@RequestBody MultiValueMap<String, String> formData) {
    
    return "Welcome to the post method with multi part form data. Printing whatever is present in the body " +  formData;
}

但是,无论何时我发送带有邮递员表格数据的请求。我得到了这个回复

  "timestamp": "2020-07-02T05:10:40.320+00:00",
"status": 415,
"error": "Unsupported Media Type",
"message": "",
"path": "/postmultipartformdata"

可能我缺少一些非常简单的东西。

最好的问候

Saurav

3 个答案:

答案 0 :(得分:1)

您需要使用@RequestParam而不是@RequestBody,并且如果要发送的内容实际上是文件,请将其映射到MultipartFile对象,在您的情况下可能不会是必需的,但是由于您的问题不清楚,您要发送的数据的种类包括在内,例如:

@PostMapping(value = "/postmultipartformdata" , consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String postFormData(@RequestParam("file") MultipartFile file,
        RedirectAttributes redirectAttributes) {

    yourService.store(file);
    redirectAttributes.addFlashAttribute("message",
            "You successfully uploaded " + file.getOriginalFilename() + "!");

    return "redirect:/";
}

通常,我们使用MultipartFile表示多部分请求中收到的上载文件。

答案 1 :(得分:1)

您也可以使用@RequestPart而不是@RequestBody在多部分请求中获取所需部分。

类似:

@RequestPart LinkedMultiValueMap<String, String> formData

由于Spring很难实例化LinkedMultiValueMap,因此我也切换到具体类MultiValueMap

然后将formDataContent-Type: application/json一起发送。

答案 2 :(得分:0)

您必须使用@RequestParam而不是@RequestBody。 由于它是表单数据,因此将使用请求参数而不是请求正文来对其进行处理。

这是我的更正方法:

@PostMapping(value = "/postmultipartformdata", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String postFormData(@RequestParam MultiValueMap<String, String> formData) {
        return "Welcome to the post method with multi part form data. Printing whatever is present in the body " + formData;
}

命令

curl --location --request POST 'http://localhost:8080/status/postmultipartformdata' \
--form 'a=a' \
--form 'b=b' \
--form 'c=c'

输出:

Welcome to the post method with multi part form data.
Printing whatever is present in the body {a=[a], b=[b], c=[c]}

参考:

What is difference between @RequestBody and @RequestParam?