如何使用Spring Rest和reactjs在MySQL数据库中保存图像或从中获取图像

发布时间:2020-07-07 17:39

帮助我使用react和spring rest创建应用程序以存储和从MySQL数据库获取图像

回答1

看看Spring Content,这是一个社区项目,它为内容提供了Java和REST API之类的Spring数据;即文件,图像和视频。它提供了几个接口来直接或通过与Spring Data实体关联来管理内容。具有几个用于支持不同类型存储的模块,包括用于将内容存储为BLOB的JPA。还具有用于版本控制的扩展API,可将内容呈现为不同的格式和全文搜索。

有了Spring Boot,添加到项目中就很容易了。

pom.xml

   <!-- other dependencies -->
   ...

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

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

YourEntity.java

public class YourEntity {
   
   ... existing fields...
   
   @ContentId
   private UUID contentId;

   @ContentLength
   private Long contentLen;

   @MimeType
   private String mimeType;
}

ImageContentStore.java

@StoreRestResource(path = "images")
public interface ImageContentStore extends ContentStore<YourEntity, UUID> {
}

这是使用REST端点配置应用程序以管理数据库中与YourEntity关联的内容所需要做的全部工作。

这实际上如何工作非常类似于Spring Data。当您的应用程序启动时,Spring Content将看到spring-content-jpa依赖性,知道您想将内容存储在文件系统上并为ImageContentStore接口注入基于JPA的实现。它还将看到spring-content-rest依赖性,并注入用于ImageContentStore接口的Controlller(即REST端点)。因此,您不必自己编写任何代码。

在客户端使用时,在您的reactjs代码中,您可以像使用其他Rest API一样使用这些REST API。我不是一个有反应的人,所以我举个例子:

所以...

curl -X POST /yourEntities/{yourEntityId} -F 'file=@path/to/local/file.jpg'

会将内容path/to/local/file.jpg存储在数据库中,并将其与ID为yourEntityId的YourEntity关联。

curl /yourEntities/{yourEntityId} -H 'Accept: image/jpg'

将再次获取它,依此类推...

REST API支持完整的CRUD(以及视频流)

有入门指南和视频here。 Spring Content JPA的参考指南为here

HTH