2013-08-07 53 views
3

我想使用下面的代碼上傳文件到休息api。此代碼適用於大約20MB的文件,但較大的文件將提供OutOfMemoryError。我試圖將請求分塊,並使用多部分形式的請求,這樣我就不必將整個文件保存在內存中,但也許塊太大了?任何幫助是極大的讚賞。Android的春季文件上傳OutofMemory

final File file = new File(filePath); 
    HttpHeaders header = new HttpHeaders(); 
    header.add("x-haiku-auth", HaikuAPI.getAuthHeader()); 
    header.setContentType(MediaType.MULTIPART_FORM_DATA); 
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(
      "https://" + HaikuAPI.getDomain() + "/api/assignments") 
      .pathSegment(assignmentID + "", "submit"); 

    URI url = builder.build().toUri(); 

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

    parts.add("message[subject]", "Assignment Completed"); 
    parts.add("message[body]", message); 
    parts.add("message[assignment_id]", assignmentID + ""); 
    Uri uri = Uri.fromFile(file); 
    InputStreamResource res = new InputStreamResource(context.getContentResolver().openInputStream(uri)) { 
     @Override 
     public String getFilename() throws IllegalStateException { 
      return file.getName(); 
     } 

     @Override 
     public long contentLength() throws IOException { 
      return file.length(); 
     } 
    }; 
    parts.add("files[][file]", res); 
    parts.add("files[][filename]", file.getName()); 
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); 
    factory.setChunkSize(1024); 
    RestTemplate restTemplate = new RestTemplate(factory); 
    restTemplate.getMessageConverters().add(new FormHttpMessageConverter()); 
    HttpEntity<Object> request = new HttpEntity<Object>(parts, header); 
    restTemplate.postForLocation(url, request); 
    Log.e("f", "finished"); 
    return null; 

錯誤: dalvikvm-heap: Out of memory on a 67102090-byte allocation.

+0

http://stackoverflow.com/questions/9630430/upload-large-file-in-android-with-outofmemory-error – KOTIOS

+0

@ Stacks28這可能做到使用Spring而不是HTTPURLConnection? –

+0

我hvnt與春天哥們一起工作,所以不能建議你 – KOTIOS

回答

4

分析代碼,好像春天的Android發送之前緩衝它的數據 - 這就是爲什麼你的監督和評價辦公室。然而,有一個技巧(但到目前爲止,我只能爲上面的API級別9工作):你可以禁用它的連接工廠的緩衝,但只有當RestTemplate沒有設置ClientHttpRequestInterceptor列表(現在多麼愚蠢?) - 幸運的是你沒有設置一個。所以在你的情況下,情況非常簡單,只需在實例化後調用factory.setBufferRequestBody(false);即可。

+0

非常感謝你! –

+0

@ gunar,你保存了一天。我欠你一個人情 – francis