使用spring resttemplate上传大文件

时间:2019-12-24 01:51:42

标签: java rest file-upload large-files

对于优化大文件上传,所有标头参数都至关重要?

以下代码对我有用,但需要专家建议。

public static void main(String[] args) throws IOException {

    RestTemplate restTemplate = new RestTemplate();
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setBufferRequestBody(false);
    restTemplate.setRequestFactory(requestFactory);

    File file = new File("large-file.txt");
    MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
    MultipartInputStreamFileResource res = new MultipartInputStreamFileResource(new FileInputStream(file),"large-file.txt");
    body.add("file", res);
    body.add("name", "large-file.txt");

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    headers.setContentLength(res.contentLength());

    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
    System.out.println();
    ResponseEntity<Resource> response = restTemplate.postForEntity("http://localhost:8081/files", requestEntity,         Resource.class);
}

0 个答案:

没有答案