2017-10-17 110 views
0
將文件上傳到春天REST服務

我寫了接受多文件作爲參數小彈簧控制器無法通過RestTemplate

@PutMapping("/fileUpload") 
    public String test(@RequestParam("test") MultipartFile file) { 
     System.out.println("In controller"); 
     return file.getOriginalFilename(); 
    } 

,我使用相應的RestTemplate是

Path path = Paths.get("C:\\Users\\Foo\\Desktop", "baz.txt"); 

      FormHttpMessageConverter messageConverter = new FormHttpMessageConverter(); 
      messageConverter.addPartConverter(new ByteArrayHttpMessageConverter()); 

      RestTemplate client = new RestTemplate(); 
      client.getMessageConverters().add(messageConverter); 

      String end_url = "http://localhost:8888/test/fileUpload"; 

      HttpHeaders headers = new HttpHeaders(); 
      headers.setContentType(MediaType.MULTIPART_FORM_DATA); 

      MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>(); 

      body.add("test", new ByteArrayResource(Files.readAllBytes(path))); 

      HttpEntity<MultiValueMap<String, Object>> entity 
       = new HttpEntity<MultiValueMap<String, Object>>(body, headers); 

      client.exchange(end_url, HttpMethod.PUT, entity, String.class, new HashMap()); 

無論我嘗試什麼,都會收到以下錯誤:

Caused by: org.springframework.web.client.HttpClientErrorException: 400 null 
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE] 
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE] 
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE] 
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:621) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE] 
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:540) ~[spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE] 
    at org.controller.Runner.run(Runner.java:57) [classes/:na] 
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:776) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE] 
    ... 6 common frames omitted 

我在做什麼錯了?我曾嘗試添加所有典型的消息轉換器,如ByteArrayHttpMessageConverter,ResourceHttpMessageConverter,我也嘗試通過使用commons-fileupload

任何人都可以告訴我我在RestTemplate中做錯了什麼?

+0

你可以得到更全面的信息看服務器控制檯。我認爲'@ RequestPart'在這裏更合適,而不是'@ RequestParam',因爲它是一個文件。 – Vasan

+0

@Vasan沒有'@ RequestParam'的作品 –

回答

0

你好嗎? 嘗試修改

@PutMapping("/fileUpload") 

@PutMapping(value = "/fileUpload", consumes = "multipart/form-data") 
+1

它沒有它的工作 –