2016-10-04 393 views
2

我具有被這樣定義一個Spring控制器:RestTemplate需要MultipartFile參數「文件」是不存在

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

當我使用郵遞員,我的請求成功。當我使用RestTemplate使用另一個春天服務的請求,我得到以下錯誤:

{"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

+1

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

回答

0
<beans:bean id="multipartResolver" 
     class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
     <!-- setting maximum upload size --> 
     <beans:property name="maxUploadSize" value="100000" /> 
    </beans:bean> 

確保你已經添加在Spring配置文件中的代碼,它可能工作爲你。

+0

這應該如何幫助?該XML用於配置接收端點。但是,正如我所提到的,當使用Postman時端點工作正常。 – AndroidDev93

相關問題