【问题标题】:Required request part 'file' is not present] springboot client所需的请求部分“文件”不存在] springboot 客户端
【发布时间】:2020-08-06 16:29:36
【问题描述】:

我在客户端有这个代码:

          RestTemplate restTemplate = new RestTemplate();
          File file = new File("C:\\temp\\aadocejem.doc");
          MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();

          map.add("file", file);


          String result = restTemplate.postForObject(url+"/doc_file", map, String.class);

而这段代码就是你上面所说的:

 @PostMapping("/doc_file")
    public ResponseEntity<File> docFileV1(
        @RequestParam("file") MultipartFile originalDocFile) {

        return ResponseEntity.ok(docFileService.processDocFile(originalDocFile));

    }

它在服务器上给我的错误:已解决 [org.springframework.web.multipart.support.MissingServletRequestPartException: required request part 'file' is not present]

它在客户端给我的错误: org.springframework.web.client.HttpClientErrorException$BadRequest: 400 : [{"timestamp":"2020-04-23T10:55:32.258+0000","status": 400,"error":"Bad Request","message":"所需的请求部分'文件'不存在","trace":"org.springframework.web.multipart.support.MissingServlet... (5758 字节) ]

【问题讨论】:

    标签: spring-boot post http-request-parameters


    【解决方案1】:

    这不适用于 postForObject。

    使用 postForEntity 代替:

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART__FORM__DATA);
    
    MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
    body.add("file", new FileSystemResource(file));
    
    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
    
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.postForEntity(url+"/doc_file", requestEntity, String.class);
    

    【讨论】:

    • 我更改了它,它一直给我同样的错误:无法解析公共 org.springframework.http.ResponseEntity com.n.poc.controller 中的参数 [0] .PocController.docFileV1(org.springframework.web.multipart.MultipartFile):所需的请求部分“文件”不存在
    • 您可能必须将文件包含在资源中。 body.add("file", new FileSystemResource(file));我更新了答案
    猜你喜欢
    • 2020-04-29
    • 2017-10-11
    • 2020-09-14
    • 2018-04-18
    • 2017-10-23
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多