我想使用下面的代碼上傳文件到休息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.
http://stackoverflow.com/questions/9630430/upload-large-file-in-android-with-outofmemory-error – KOTIOS
@ Stacks28這可能做到使用Spring而不是HTTPURLConnection? –
我hvnt與春天哥們一起工作,所以不能建議你 – KOTIOS