如何使用Angular 4和Spring在数据库中存储图像 [英] How to store an image in the database using Angular 4 and Spring

查看:65
本文介绍了如何使用Angular 4和Spring在数据库中存储图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在前端使用Angular 4,在后端使用Spring,因此我想在数据库中存储一个包含图像的用户.据我所知 Blob 类型存在于 Angular 4 中,但在Spring中却不存在,而 byte 类型存在于 Spring ,但它不在Angular 4中.如何使用REST API将图像从前端传输到后端.

I'm using Angular 4 for the Front-end and Spring for the Back-end and I wanna store a user which contains an image in my database. As i know the type Blob exists in Angular 4 but it doesn't in Spring, and the type byte exists in Spring but it doesn't in Angular 4. How can I transfer my image from the Front-end to the Back-end using REST API.

这是我的实体:

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;

这是我的网络服务:(在添加照片之前可以正常使用):

This is my web service :(it works normally before adding the 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);
}

最后是我的打字稿:

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;
}

如果有任何更正,请通知我.预先谢谢你

If there is any rectifications please let me know. Thank you in advance

推荐答案

如果确实需要将图像存储在数据库中,那么可以使用LOB数据类型:

If you are really in the case when it makes a sense to store the images in the database, then you can you use LOB datatype:

// File content
@Lob
private Blob image;

在前端使用FormData通过REST API将文件传递到后端,请参见示例

On the Front-end use FormData to pass the file to the Back-end using REST API, see a sample here

P.S.您可能需要将映像存储在文件系统中,并将其路径保留在数据库中.请参阅为什么.

P.S. You might probably want to store an image in the file system and keep its path in the database. Please see why.

这篇关于如何使用Angular 4和Spring在数据库中存储图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆