[Spring] File 을 MultipartFile 로 변경
by 코박7https://stackoverflow.com/questions/16648549/converting-file-to-multipartfile
스택오버 플로우에서 file 을 MultipartFile 로 변경하는 방법을 소개했다.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.mock.web.MockMultipartFile;
Path path = Paths.get("/path/to/the/file.txt");
String name = "file.txt";
String originalFileName = "file.txt";
String contentType = "text/plain";
byte[] content = null;
try {
content = Files.readAllBytes(path);
} catch (final IOException e) {
}
MultipartFile result = new MockMultipartFile(name,
originalFileName, contentType, content);
MockMultipartFile 을 사용하여 파일을 생성, Controller 로 넘김.
// dto 에선 multipartFile 을 받는다.
public static class Test {
private MultipartFile file;
}
dto 에서 변환 과정에서 오류 발생.
org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class java.io.ByteArrayInputStream]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.vehicle.web.rest.dto.TestDTO$PostDto["file"]->org.springframework.mock.web.MockMultipartFile["inputStream"])
해결
@PostMapping
public ResponseEntity<Long> create(@Valid @RequestPart(value = "dto") UserDTO.PostDto request, BindingResult bindingResult,
@RequestPart(value = "file") MultipartFile file,
@RequestParam("userId") String userId) throws URISyntaxException, IOException, ExecutionException, InterruptedException {
if (bindingResult.hasErrors()) {
throw new BadRequestAlertException("A required value is missing.", ENTITY_NAME, HttpStatus.BAD_REQUEST.toString());
}
UserDTO.PostDto response = userMapper.toDto(userService.create(userMapper.toEntity(request), file, userId));
return ResponseEntity.created(new URI("/api/user/" + response.getUserId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME,
response.getUserId().toString()))
.body(response.getUserId());
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
Resource resource = new FileSystemResource(file.toPath());
map.add("file", resource);
map.add("dto", dto);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, httpHeaders);
- 테스트 코드에선 header 설정 과 Resource, map 을 사용하며, RestTemplate 를 사용해서 넘겨줬음.
- 위 file 로 넘겨준 객체가 정상적으로 매핑되는걸 확인.
'spring' 카테고리의 다른 글
[Spring] 간단하게 POST 요청 보내기 (2) | 2023.07.25 |
---|---|
[Spring] CORS 란? CORS 해결 (0) | 2023.07.13 |
[Spring] Embedded kafka 테스트 진행 (0) | 2023.07.07 |
[Spring] @Vaild 어노테이션을 리스트에 적용시켜보자 (0) | 2023.06.25 |
[Spring] validation 어노테이션으로 간단한 유효성 검사 (0) | 2023.06.18 |
블로그의 정보
코딩박스
코박7