[DEV] 기록

[Java] File을 MultipartFile로 변환하는 함수

꾸준함. 2022. 4. 12. 22:50

개요

txt 파일을 생성한 뒤 RestTemplate을 통해 파일 인스턴스로 보내야 하는데 MultipartFile 객체로 변환해서 보내야 했기 때문에 간단하게 함수를 작성해봤습니다.

 

소스 코드


private MultipartFile convertFileToMultipartFile(File file) throws IOException {
FileItem fileItem = new DiskFileItem("file"
, Files.probeContentType(file.toPath())
, false, file.getName()
, (int) file.length(),
file.getParentFile());
try {
InputStream is = new FileInputStream(file);
OutputStream os = fileItem.getOutputStream();
IOUtils.copy(is, os);
} catch (IOException e) {
log.error("[convertFileToMultipartFile] error {}", e.getMessage());
throw new IOException(e);
}
return new CommonsMultipartFile(fileItem);
}
view raw .java hosted with ❤ by GitHub

반응형