2013-04-11 88 views
2

我一直在試圖瞭解如何使用RoboSpice與Spring上傳文件到我的服務器,但我找不到一個有效的例子。從一個例子中,我沒有發現,我構建:RoboSpice文件上傳與Android上的春天

class UploadJsonRequest extends SpringAndroidSpiceRequest<APIResponseUpload> { 

      public UploadJsonRequest() { 
       super(APIResponseUpload.class); 
      } 

      @Override 
      public APIResponseUpload loadDataFromNetwork() throws Exception { 

       MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>(); 
       for(org.calflora.observer.model.Attachment a : o.attachments){ 

        parts.add(a.name, new FileSystemResource(a.localPath)); 

       } 
       //parts.add("record", base); 
       return getRestTemplate().postForObject(URI, parts, APIResponseUpload.class); 
      } 
    } 
    return new UploadJsonRequest(); 

然而,這給我的錯誤:

Caused by: org.springframework.web.client.HttpClientErrorException: 404 err: org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/json;charset=UTF-8 

好了,這似乎表明,我需要做一些額外的指示數據應該使用multipart/form-data來傳輸。如果這是正確的,這是如何完成的?如果這不正確,那麼規範的方法是什麼,因爲這顯然是一種常見的需求?

+0

你有看到代碼嗎? http://stackoverflow.com/q/15769019/321354 – rciovati 2013-04-11 09:03:53

+0

是的。您會注意到,該代碼與我的代碼幾乎相同。我嘗試過使用它,但是它包含一個對'UploadRequestModel'的引用,它沒有被解釋,並且似乎不存在於我已經安裝的任何jar中 - 所以顯然它不會構建。你能給我一些關於這方面的見解嗎? – deepwinter 2013-04-11 18:18:08

回答

4

在我的情況下,以下解決了這個問題

HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(parts, requestHeaders); 

RestTemplate restTemplate = getRestTemplate(); 
restTemplate.getMessageConverters().add(new FormHttpMessageConverter()); 
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); 

return restTemplate.postForObject(URI, requestEntity, APIResponseUpload.class); 

但是,根據文檔的春天,這不應該是必要手動設置信息轉換器。