0

i want to ask how to do the following things: When user creates an account, i want the backend to set a default-user-profile picture which i want to store in static/images/image-name.jpg. I will post my Image entity and UserService

Image Entity

public class Image {
    @Id
    @Column(name = "image_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long imageId;

    @Column(name = "image_name")
    private String imageName;

    @Column(name = "image_type")
    private String imageType;

    @Lob
    @Column(name = "image")
    private byte[] image;

    @OneToOne(mappedBy = "userProfilePicture")
    private User userProfilePicture;

UserServiceImpl

    @Override
    public User createUser(UserDto userDto) {
        User user = new User();
        User userExists = userRepository.findUserByEmail(userDto.getEmail());
        if(userExists == null) {
            user.setEmail(userDto.getEmail());
            user.setName(userDto.getName());
            user.setPassword(bCryptPasswordEncoder.encode(userDto.getPassword()));
            user.setRoles(roleRepository.findUsersByRole("USER"));
            user.setDateAdded(LocalDateTime.now());

            userRepository.save(user);
        } else {
            throw new ApiRequestException("Email exists!");
        }
        return user;
    }

How can i get the image from static/images? and set it in the service. Thanks in advance if you need something more specific from the code i will paste it here. Cheers!

Rumen
  • 57
  • 1
  • 11

1 Answers1

1

You can read the file using Files.readAllBytes() as shown in this answer: https://stackoverflow.com/a/5083666/7271045

Then, when you have the image loaded in your byte[] variable, just set it to the class field.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Jose Esparza
  • 292
  • 1
  • 8