我试图使用以下代码将文件上传到rest api。这段代码适用于大小不超过20MB的文件,但更大的文件会导致OutOfMemoryError
。我正在尝试对请求进行分块,并使用多部分表单请求,以便无需在内存中保留整个文件,但也许块太大了?如有帮助,不胜感激。
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: 尝试分配 67102090 字节的内存空间失败,可能是由于内存不足所致。