1

我正在尝试创建一个电影数据库网络应用程序。每部电影都应该有一张海报图片。我不知道如何使用 Spring Data REST 正确地将图像提供给前端。

电影.java

import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.io.File;
import java.sql.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Data
@Entity
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Movie {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String director;
    private Date releaseDate;
    private File posterFile;

    @ManyToMany
    @JoinTable(
            name = "MOVIE_GENRES",
            joinColumns = @JoinColumn(name = "MOVIE_ID"),
            inverseJoinColumns = @JoinColumn(name = "GENRE_ID"))
    private Set<Genre> genres = new HashSet<>();

    @OneToMany
    @MapKeyColumn(name = "ACTOR_ROLE")
    private Map<String, Actor> cast = new HashMap<>();

    public Movie(String title) {
        this.title = title;
    }

    public void addActor(String role, Actor actor) {
        cast.put(role, actor);
    }

    public void removeActor(String role) {
        cast.remove(role);
    }

    public void addGenre(Genre genre) {
        genres.add(genre);
    }

    public void removeGenre(Genre genre) {
        genres.remove(genre);
    }
}

我不能在电影 bean 中使用字节数组,因为它太大而无法保存在数据库中。我可以存储 File 对象或 Path 对象或包含路径的 String: private File posterFile; 问题是,它将保存一个本地路径,如"C:\user\documents\project\backend\images\posterxyz.png". 当我尝试在前端将此路径用作 img-src 时,出现错误“不允许加载本地资源”。我的意思是,无论如何,这听起来像是一种愚蠢的做法。我只是不知道这样做的正确方法是什么。

这是电影资料库。我在后端使用 Spring Data REST 以超媒体应用程序语言格式生成 JSON。

MovieRepository.java

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "movies", path = "movies")
public interface MovieRepository extends PagingAndSortingRepository<Movie, Long> {

}
4

3 回答 3

2

我会:

通过向字段添加注释来防止posterFile属性被序列化。@JsonIgnore

@JsonIgnore
private File posterFile;

您也可以通过 Jackson 混合类来执行此操作,以避免使用 Json 处理指令“污染”您的实体,但您需要自己研究。

向资源表示添加自定义链接,允许客户端按需获取图像数据。例如/movies/21/poster

有关如何将自定义链接添加到资源的详细信息,请参见此处:

Spring Data Rest 资源上的自定义链接

并且专门用于创建指向 Spring MVC 控制器的链接:

https://docs.spring.io/spring-hateoas/docs/0.24.0.RELEASE/api/org/springframework/hateoas/mvc/ControllerLinkBuilder.html

https://stackoverflow.com/a/24791083/1356423

创建一个标准 Spring MVC 控制器,该控制器绑定到您的自定义链接指向的路径,它将读取文件数据并流式传输响应。

例如

@Controller
public MoviePosterController{

    @GetMapping(path="/movies/{movieId}/poster")
    //https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.web for auto resolution of path var to domain Object
    public @ResponseBody byte[] getPoster(@PathVariable("movieId") Movie movie, HttpServletResponse response){
        File file = movie.getPosterFile();
        //stream the bytes of the file
        // see https://www.baeldung.com/spring-controller-return-image-file
        // see https://www.baeldung.com/spring-mvc-image-media-data
    }
}
于 2019-06-19T14:31:34.433 回答
1

这对于 Spring Data/REST 来说是不可能的,因为它专注于结构化数据;即大部分的表格和关联。是的,您可以按照其他答案中的说明跳过一些障碍,但是还有一个名为Spring Content的相关项目可以准确解决这个问题域。

Spring Content 提供与 Spring Data/REST 相同的编程范式,只是针对非结构化数据;即图像、文档、电影等。因此,使用此项目,您可以将一个或多个“内容”对象与 Spring Data 实体相关联,并通过 HTTP 管理它们,就像使用 Spring Data 实体一样。

添加到您的项目中非常简单,如下所示:

pom.xml(也可以使用引导启动器)

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

配置

@Configuration
@EnableJpaStores
@Import("org.springframework.content.rest.config.RestConfiguration.class")
public class ContentConfig {

    // schema management (assuming mysql)
    // 
    @Value("/org/springframework/content/jpa/schema-drop-mysql.sql")
    private Resource dropContentTables;

    @Value("/org/springframework/content/jpa/schema-mysql.sql")
    private Resource createContentTables;

    @Bean
    DataSourceInitializer datasourceInitializer() {
        ResourceDatabasePopulator databasePopulator =
                new ResourceDatabasePopulator();

        databasePopulator.addScript(dropContentTables);
        databasePopulator.addScript(createContentTables);
        databasePopulator.setIgnoreFailedDrops(true);

        DataSourceInitializer initializer = new DataSourceInitializer();
        initializer.setDataSource(dataSource());
        initializer.setDatabasePopulator(databasePopulator);

        return initializer;
    }
}

要关联内容,请将 Spring Content 注释添加到您的 Movie 实体。

电影.java

@Entity
public class Movie {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
    .. existing fields...    
  // private File posterFile; no longer required

  @ContentId
  private String contentId;

  @ContentLength
  private long contentLength = 0L;

  // if you have rest endpoints
  @MimeType
  private String mimeType = "text/plain";
}

创建一个“商店”:

MoviePosterContentStore.java

@StoreRestResource(path="moviePosters")
public interface MoviePosterContentStore extends ContentStore<Movie, String> {
}

这就是创建 REST 端点 @ 所需的全部内容/moviePosters。当您的应用程序启动时,Spring Content 将查看 Spring Content JPA 的依赖项,查看您的MoviePosterContentStore接口并为 JPA 注入该接口的实现。它还将查看 Spring Content REST 依赖项并注入@Controller将 HTTP 请求转发到 MoviePosterContentStore 的实现。这使您不必自己实施任何这些,我认为这就是您所追求的。

所以...

使用注入的 REST API 管理内容:

curl -X POST /moviePosters/{movieId}-F 文件=@/path/to/poster.jpg

将图像存储在数据库中(作为 BLOB)并将其与 id 为的电影实体相关联movieId

curl /moviePosters/{movieId} -H "Accept: image/jpeg"

将再次获取它等等...支持所有 CRUD 方法和视频流以及顺便说一句!

这里有一些入门指南。JPA 的参考指南在这里这里有一个教程视频。编码位从大约 1/2 处开始。

还有几点: - 如果您使用 Spring Boot Starters,那么大部分情况下您不需要 @Configuration。
- 就像 Spring Data 是一种抽象一样,Spring Content 也是如此,因此您不限于将海报图像作为 BLOB 存储在数据库中。您可以将它们存储在文件系统或云存储(如 S3)或 Spring Content 支持的任何其他存储中。

HTH

于 2019-06-20T04:02:47.403 回答
0
@RestController 
// Becareful here, never use @RepositoyRestController.it will be got Error look like NoConverter for.....

@RequiredArgsConstructor
// becase you use  Path rootLocation, don't use @AllArgsContructor
public class StorageController {

    private final StorageRepository storageRepository;

    @Value("${file.upload.path}")
    private Path rootLocation;

    @Bean
    public RepresentationModelProcessor<EntityModel<Storage>> storageProcessor() {
        return new RepresentationModelProcessor<EntityModel<Storage>>() {
            @Override
            public EntityModel<Storage> process(EntityModel<Storage> model) {
                model.add(
                        linkTo(methodOn(StorageController.class).look(model.getContent().getId())).withRel("view")
                );
                return model;
            }
        };
    }

    @GetMapping(path = "storages/{id}/view")
    public ResponseEntity<?> look(@PathVariable final Long id) {
        Storage storage = storageRepository.findById(id).orElseThrow(RuntimeException::new);
        Path path = rootLocation.resolve(storage.getPath());
        Resource resource = null;
        try {
            resource = new UrlResource(path.toUri());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Error!!!!");
        }

        if (resource.exists() || resource.isReadable()) {
            return ResponseEntity
                    .ok()
                    .header(HttpHeaders.CONTENT_TYPE, storage.getMime())
                    .body(resource);
        } else {
            throw new RuntimeException("Error!!!");
        }
    }
}
于 2021-11-30T02:11:35.640 回答