80.2 Get user profile image - by userId (#9)

This commit is contained in:
Art
2021-09-10 16:11:57 +03:00
parent 1f14f925cf
commit c632829374
4 changed files with 40 additions and 3 deletions

View File

@ -117,6 +117,13 @@ public class UserResource {
return profileImage;
}
@GetMapping(path = "image/profile/{userId}/{filename}", produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] getProfileImageByUserId(@PathVariable String userId, @PathVariable String filename) throws IOException {
byte[] profileImage = userService.getImageByUserId(userId, filename);
log.debug("File size: {}", profileImage.length);
return profileImage;
}
private void authenticate(String username, String password) {
Authentication auth = new UsernamePasswordAuthenticationToken(username, password);
authenticationManager.authenticate(auth);

View File

@ -30,4 +30,6 @@ public interface UserService extends UserDetailsService {
byte[] getProfileImage(String username) throws IOException;
byte[] getImageByUserId(String userId, String filename) throws IOException;
}

View File

@ -220,9 +220,14 @@ public class UserServiceImpl implements UserService {
@Override
public byte[] getProfileImage(String username) throws IOException {
User user = findByUsername(username);
Path userFolder = Paths
.get(USER_FOLDER, user.getUserId(), USER_IMAGE_FILENAME);
return Files.readAllBytes(userFolder);
return getImageByUserId(user.getUserId(), USER_IMAGE_FILENAME);
}
@Override
public byte[] getImageByUserId(String userId, String filename) throws IOException {
Path userProfileImagePath = Paths
.get(USER_FOLDER, userId, filename);
return Files.readAllBytes(userProfileImagePath);
}
private void validateNewUsernameAndEmail(String username, String email) {

View File

@ -729,6 +729,29 @@ class UserResourceUnSecureTest extends BaseUserTest {
.hasFieldOrPropertyWithValue("message", "Error occurred while processing file".toUpperCase());
}
@Test
void getImageById_correct() throws IOException {
//given
String username = user.getUsername();
uploadProfileImage(username);
String profileImageUrlFull = user.getProfileImageUrl();
String profileImageUrl = profileImageUrlFull.substring(profileImageUrlFull.indexOf("/user/image/profile"));
log.debug("Image URL: {}", profileImageUrl);
//when
RequestEntity<Void> requestEntity = RequestEntity.get(profileImageUrl)
.accept(MediaType.IMAGE_JPEG)
.build();
var responseEntity = restTemplate.exchange(requestEntity, new ParameterizedTypeReference<byte[]>() {
});
//then
log.debug("Response Entity: {}", responseEntity);
assertThat(responseEntity.getStatusCode()).isEqualTo(OK);
assertThat(responseEntity.getBody()).hasSize(52);
}
private void uploadProfileImage(String username) throws IOException {
MultipartFile profileImage = new MockMultipartFile("profileImage", "test.txt",