英文:
Spring boot rest setting user default profile image on register
问题
我想问如何完成以下任务:当用户创建账户时,我希望后端设置一个默认的用户个人头像,我希望将它存储在static/images/image-name.jpg。我会贴出我的Image实体和UserService。
Image实体
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());
// 设置默认头像
Image defaultImage = getDefaultImage(); // 调用获取默认图片的方法
user.setUserProfilePicture(defaultImage);
userRepository.save(user);
} else {
throw new ApiRequestException("Email exists!");
}
return user;
}
如何从static/images获取图片并在服务中设置它?如果需要代码中的更具体内容,请贴在这里。谢谢提前帮助,如果你需要更多信息,请告诉我。祝好!
英文:
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!
答案1
得分: 1
你可以使用Files.readAllBytes()
来读取文件,就像这个回答中所示:https://stackoverflow.com/a/5083666/7271045
然后,当你将图像加载到你的byte[]
变量中后,只需将它设置到类字段中。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论