如何使用Angular 4和Spring在数据库中存储图像?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (80)

我在前端使用Angular 4,后端使用Spring,我想在我的数据库中存储一个包含图像的用户。我知道Bloular存在于Angular 4中,但它不存在于Spring中,并且类型字节存在于Spring中,但它不存在于Angular 4中。如何将我的图像从前端传输到后端使用REST API。

entity:

import java.sql.Blob;
@Entity
@Table(name = "USER_OAUTH", schema = "OAUTH")
public class UserOauth implements java.io.Serializable {
 private long idUser;
 private String username;
 private String firstName;
 private String lastName;
 private String adrEmail;
 private int isAdAccount;
 private Date lastConnection;
 private String password;
 private boolean enabled;
 private int attempts;
 private Blob photo;

@Lob
@Column(name = "PHOTO", length = 10000000)
public Blob getPhoto() {
    return photo;
}

DTO:

public class UserDTO implements java.io.Serializable {

 private long idUser;
 private String username;
 private String firstName;
 private String lastName;
 private String adrEmail;
 private int isAdAccount;
 private Date lastConnection;
 private String password;
 private boolean enabled;
 private Blob photo;

网络服务:

// Add a new user;
@RequestMapping(value = "/users", method = RequestMethod.POST)
public UserDTO addUser(@RequestBody final UserDTO user) throws Exception {
    return modelMapper.map(userService.saveUser(modelMapper.map(user, UserOauth.class)), UserDTO.class);
}

Typescript:

export class UserData {
  public  idUser: number;
  public  username: string;
  public  firstName: string;
  public  lastName: string;
  public  adrEmail: string;
  public  isAdAccount: boolean;
  public  lastConnection: Date;
  public  password: string;
  public  enabled: boolean;
  public  photo:Blob;
}
提问于
用户回答回答于

如果你真的遇到将图像存储在数据库中的意义,那么你可以使用LOB数据类型:

// File content
@Lob
private Blob image;

在前端使用FormData使用REST API将文件传递到后端。

用户回答回答于

在TypeScript / Angular中,你可以声明你的字段,如下所示: img: File;

你在Spring中的RestController中的DTO应该使用private final byte[] img;,最后也是你的实体:

@Lob
@Column(name = "IMG", length = 10000000)
private byte[] img;

扫码关注云+社区

领取腾讯云代金券