2013-08-07 54 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