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

时间:2018-06-07 10:04:47

标签: spring angular rest

我在前端使用Angular 4,后端使用Spring,我想在我的数据库中存储一个包含图像的用户。 我知道 Blob 类型存在于 Angular 4 中,但它不存在于Spring中,字节类型存在于 Spring < / strong>但它不在Angular 4中。 如何使用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;

这是我的网络服务:(在添加照片之前它正常工作):

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

如果有任何整改,请告诉我。 提前谢谢

3 个答案:

答案 0 :(得分:1)

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

// File content
@Lob
private Blob image;

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

P.S。 您可能希望将图像存储在文件系统中并将其路径保留在数据库中。请参阅why

答案 1 :(得分:0)

在TypeScript / Angular中,您可以声明以下字段:img: File;

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

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

答案 2 :(得分:0)

假设您正在使用Spring Data,那么Spring Content JPA比直接使用@Lob并编写自己的@Controller以处理多部分/表单数据POST要容易得多。

添加以下依赖项:

  

的pom.xml

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title></title>
<link href="http://localhost/rentcar/bootstrap- 
4.1.1/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php  
session_start();//session starts here  
?>  <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark mb-4">

  <a class="navbar-brand" href="index.php"><img src="images/logo.jpg" 
width="30" height="30"> KY Rentalcar</a> 
  <button class="navbar-toggler" type="button" data-toggle="collapse" data- 
 target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria- 
 expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarsCollapse">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item">
        <a class="nav-link" href="index.php?page=car_price">Cars</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="index.php?page=selectReview">Review</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="map.php">Pickup Station</a>
      </li> 
      <li class="nav-item">
   <a class="nav-link" href="index.php?page=selectChatView">
    Chat</a>
      </li>
    <?php
    if (!isset($_SESSION['username'])){
    ?>
    </ul>
       <a href="index.php?page=loginView">
        <button class="btn btn-outline-success my-2 my-sm-0">
        Login
        </button>
      </a>
    <?php
    }else if ($_SESSION['status']=='customer'){
    ?>
    <li class="nav-item">
        <a class="nav-link" href="index.php?page=selectMy_pageView">My 
    Information</a>
      </li>
    <li class="nav-item">
        <a class="nav-link" href="index.php? 
   page=selectMy_reservationView">My Reservation</a>
      </li>
    <li class="nav-item">
        <a class="nav-link" href="index.php?page=insertReservationView">New 
    Reservation</a>
      </li>

    <ul>  
    <li class="nav-link disabled" style="color:white;">
       <?php
         if (isset($_SESSION['username'])){
          echo "Welcome, ".$_SESSION['username']."!";
        }
       ?>
      <span class="sr-only">(current)</span>
     </li>
     </ul>

      <ul>
       <a href="index.php?page=logoutDo">
        <button class="btn btn-outline-success my-2 my-sm-0">
        Logout
        </button>
      </a>
      </ul>
    <?php
    }else if ($_SESSION['status']=='admin'){
    ?>
    <li class="nav-item">
        <a class="nav-link" href="index.php?page=selectCar_typeView">Car 
    Type Management</a>
      </li> 
    <li class="nav-item">
        <a class="nav-link" href="index.php? 
    page=selectCustomerView">Customer Data</a>
       </li>
    <li class="nav-item">
        <a class="nav-link" href="index.php? 
    page=selectReservationView">Reservation Data</a>
     </li>


    <ul>  
    <li class="nav-link disabled" style="color:white;">
       <?php
         if (isset($_SESSION['username'])){
          echo "Welcome, ".$_SESSION['username']."!";
        }
       ?>
      <span class="sr-only">(current)</span>
     </li>
     </ul>

      <ul>
       <a href="index.php?page=logoutDo">
        <button class="btn btn-outline-success my-2 my-sm-0">
        Logout
        </button>
      </a>
      </ul>
    <?php
    }
    ?>
    </div>
   </nav>   
   <!-- Bootstrap core JavaScript
   ================================================== -->
   <!-- Placed at the end of the document so the pages load faster -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
  integrity="sha384- 
  q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
  crossorigin="anonymous"></script>
  <script>window.jQuery || document.write('<script 
  src="http://localhost/rentcar/bootstrap-4.1.1/assets/js/vendor/jquery- 
   slim.min.js"><\/script>')</script>
  <script src="http://localhost/rentcar/bootstrap- 
  4.1.1/assets/js/vendor/popper.min.js"></script>
 <script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> 
   </script>
<script src="http://localhost/rentcar/bootstrap- 
    4.1.1/dist/js/bootstrap.min.js"></script>
 </body>
 </html>

将以下属性添加到UserOauth实体,以便内容可以与之关联。

  

UserOAuth.java

   <!-- Java API -->
   <dependency>
      <groupId>com.github.paulcwarren</groupId>
      <artifactId>spring-content-jpa-boot-starter</artifactId>
      <version>0.0.11</version>
   </dependency>
   <!-- REST API -->
   <dependency>
      <groupId>com.github.paulcwarren</groupId>
      <artifactId>spring-content-rest-boot-starter</artifactId>
      <version>0.0.11</version>
   </dependency>

创建一个@Entity public class UserOAuth { ...existing fields... @ContentId private String contentId; @ContentLength private long contentLength = 0L; // if you have rest endpoints @MimeType private String mimeType; // no need for Blob (相当于BLOB的JpaRepository):

  

UsersOAuthContentStore.java

ContentStore

(我假设你有数据库连接的必备bean)。

当您运行应用程序时,Spring Content将看到@StoreRestResource(path="usersPhoto") public interface UsersPhotoContentStore extends ContentStore<UserOAuth, String> { } 接口和UsersPhotoContentStore依赖项,并为您注入此接口的JPA实现。它还将看到spring-content-jpa依赖项并添加一个@Controller实现,它还将GET,PUT,POST和DELETE REST请求转发到spring-content-rest。这样您就不必再写了。 REST端点将在UsersPhotoContentStore处提供,因此......

/usersPhotos

将上传photo.jpg并将其与您的实体相关联。和

curl -X POST -F "image=@/home/user1/Desktop/photo.jpg" /usersPhotos/{userOAuthId}会再次获取它。

HTH