首页 > 解决方案 > MissingServletRequestPartException:所需的请求部分“文件”不存在 Springboot

问题描述

我有一个执行文件上传的控制器,我正在尝试从另一个服务向控制器端点发布请求。

@RequestMapping(path = "/upload/{id}", method = RequestMethod.POST)
    public String uploadBaseImage(@RequestParam("data") String imageData, @RequestParam("file") MultipartFile file,@PathVariable("id") String id)
            throws Exception {
        String imageUrl = feedHandler.UploadAndSetImageUrl(imageData, file,Integer.parseInt(id));
        return imageUrl;
    }

我调用上述端点的代码

public SupplierFeedResponse uploadBaseFeedImage(String data, MultipartFile file, String supplierId) throws IOException {
        String uploadBaseFeedEndpoint = uploadFeedEndpoint+Constants.FEED_SERVICE_BASE_FEED_UPLOAD_URI+supplierId;
        SupplierFeedResponse supplierFeedResponse =  new SupplierFeedResponse();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", new ByteArrayResource(file.getBytes()));
        body.add("data", data);

        log.info("Request body : "+body.toString());

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.postForEntity(uploadBaseFeedEndpoint, requestEntity, String.class);
        return supplierFeedResponse;

    }

我收到以下错误,不知道原因:

[MissingServletRequestPartException: Required request part 'file' is not present]

环顾了一段时间,没有解决办法。

标签: javaspring-bootmultipartform-dataresttemplate

解决方案


可能您的请求中缺少file参数,因此您必须在请求中考虑file参数。您也可以在其中添加新属性(require),@RequestParam例如@RequestParam(value = "file", required = false). 属性的目的required,使请求参数是必需的(如果为真)或可选的(如果为假)。


推荐阅读