【问题标题】:RestTemplate required MultipartFile parameter 'file' is not presentRestTemplate 所需的 MultipartFile 参数“文件”不存在
【发布时间】:2017-02-12 13:13:57
【问题描述】:

我有一个这样定义的 Spring 控制器:

@RequestMapping(method = RequestMethod.POST, value = "/upload")
    @ResponseBody
    public void handleFileUpload2(@RequestParam("file") MultipartFile file){

当我使用邮递员时,我的请求成功。当我使用 RestTemplate 从另一个 Spring 服务发出请求时,我收到以下错误:

{"timestamp":1475579425804,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required MultipartFile parameter 'file' is not present","path":"/upload"}

这是我使用 RestTemplate 发出请求的方式。

public void uploadFile(MultipartFile file, String url) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();

    body.add("file", new ByteArrayResource(file.getBytes()));

    RestTemplate restTemplate = new RestTemplate();
    HttpEntity requestEntity = new HttpEntity(body, headers); 
    restTemplate.exchange(url, method, requestEntity, String.class);
}

我无法弄清楚我在这里做错了什么。 This 问题似乎表明您需要添加一些 xml 以使其正常工作,但由于它可以从 Postman 工作,我相信实际问题与我如何使用 RestTemplate 进行其余调用有关。

如果我打印出requestEntity,我会得到以下信息:

<{file=[resource loaded from byte array]},{Content-Type=[multipart/form-data]}>

我正在使用spring-web 4.1.4.RELEASE

【问题讨论】:

  • HttpEntity requestEntity = new HttpEntity(headers); restTemplate.exchange(url, method, requestEntity, String.class, body);

标签: spring resttemplate


【解决方案1】:
<beans:bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- setting maximum upload size -->
        <beans:property name="maxUploadSize" value="100000" />
    </beans:bean>

确保你已经在你的 spring 配置文件中添加了这个代码,它可能对你有用。

【讨论】:

  • 这应该有什么帮助?此 XML 用于配置接收端点。但是,正如我提到的,端点在使用 Postman 时可以正常工作。
【解决方案2】:

现在回答这个问题已经很晚了。但我的回答可能对正在寻找这个问题的人有所帮助。

我遇到了类似的问题,更改读取文件的方式为我解决了问题。

body.add("file",new FileSystemResource(TEST_PDF_FILE_PATH));

【讨论】:

    【解决方案3】:

    代替

    body.add("file", new ByteArrayResource(file.getBytes()));
    

    试试

    body.add("file", file.getResource());
    

    这对我有用。

    【讨论】:

      猜你喜欢
      • 2014-05-08
      • 1970-01-01
      • 2021-04-12
      • 2018-04-05
      • 2013-09-20
      • 2015-06-11
      • 2014-09-10
      • 1970-01-01
      • 2019-03-14
      相关资源
      最近更新 更多