개요
최근에 개발하는 프로젝트에서 파일 업로드 및 생성을 별도 인스턴스에서 진행하고 있어 RestTemplate을 사용해야 했습니다.
이번 게시글에서는 RestTemplate을 통해 MultipartFile을 보내는 방법을 짧게 공유해보겠습니다.
코드
1. RestTemplate을 통해 파일 보내는 코드
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void sendMultipartFile(MultipartFile file) { | |
String url = baseUrl + "/file/upload"; | |
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); | |
ByteArrayResource contentsAsResource = new ByteArrayResource(modelFile.getBytes()){ | |
@Override | |
public String getFilename(){ | |
return file.getOriginalFilename(); | |
} | |
}; | |
body.add("file", contentsAsResource); | |
HttpHeaders headers = new HttpHeaders(); | |
headers.setContentType(MediaType.MULTIPART_FORM_DATA); | |
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers); | |
try { | |
restTemplate.postForEntity(url, requestEntity, Void.class); | |
} catch (Exception e) { | |
log.error("[sendMultipartFile] ERROR {}", e.getMessage()); | |
} | |
} |
2. RestTemplate이 호출하는 컨트롤러
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@PostMapping(value = "/file/upload") | |
public void uploadFile(@RequestParam(value = "file") MultipartFile file) throws FileUploadException { | |
log.info("resttemplate request successful"); | |
fileStorageService.uploadFile(file); | |
} |
3. 적용했던 RestTemplate Config
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Configuration | |
public class RestTemplateConfig { | |
private static final int CONNECTION_TIMEOUT = 2000; | |
private static final int READ_TIMEOUT = 5000; | |
private static final int MAX_CONN_TOTAL = 5000; | |
private static final int MAX_CONN_PER_ROUTE = 20; | |
@Bean(name = "restTemplate") | |
public RestTemplate restTemplate() { | |
// HttpComponents 사용하여 pool 설정 | |
HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); | |
httpComponentsClientHttpRequestFactory.setConnectTimeout(CONNECTION_TIMEOUT); | |
httpComponentsClientHttpRequestFactory.setReadTimeout(READ_TIMEOUT); | |
HttpClient httpClient = HttpClientBuilder.create() | |
.setMaxConnTotal(MAX_CONN_TOTAL) | |
.setMaxConnPerRoute(MAX_CONN_PER_ROUTE) | |
.build(); | |
httpComponentsClientHttpRequestFactory.setHttpClient(httpClient); | |
// logging interceptor, error handler 추가 | |
RestTemplate restTemplate = new RestTemplate( | |
new BufferingClientHttpRequestFactory(httpComponentsClientHttpRequestFactory)); | |
restTemplate.setInterceptors(Lists.newArrayList(new [커스텀 인터셉터])); | |
restTemplate.setErrorHandler([커스텀 에러 핸들러]); | |
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8)); | |
return restTemplate; | |
} | |
} |
참고
https://stackoverflow.com/questions/58344008/upload-multipartfiles-using-resttemplate
Upload MultipartFiles using RestTemplate
I have two end-points. One endpoint will receive files from Postman and should foreward the same files to another endpoint using RestTemplate. The 2nd endpoint is getting invoked, but no files.
stackoverflow.com
반응형
'[DEV] 기록' 카테고리의 다른 글
[javascript] json 이쁘게 출력하기 (2) | 2022.03.24 |
---|---|
[javascript] JSZip을 활용하여 form에 올라간 zip 파일 내 json 파일 읽기 (0) | 2022.03.16 |
[SpringBoot] ajax를 통해 파일과 json 컨트롤러로 보내는 방법 (0) | 2022.03.15 |
[SpringBoot] 대용량 엑셀 파일 생성 및 다운로드 삽질기 (6) | 2022.03.13 |
[javascript] Invalid shorthand property initializer (0) | 2022.03.04 |