I'm trying to create a movie database web app. Each movie should have a poster image. I don't know how to correctly serve images to the frontend with Spring Data REST.
Movie.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);
}
}
I can't use a byte-array in the movie bean because it is too large to be saved in the database. I could store the File object or a Path object or a String containing the path instead:
private File posterFile;
The problem is, that it will save a local path like "C:\user\documents\project\backend\images\posterxyz.png"
.
When i try to use this path as img-src in my frontend it get error "Not allowed to load local resource". I mean it sounds like a stupid way of doing this anyway. I just don't know what the correct way to do this is.
This is the Movie Repository. I'm using Spring Data REST in the backend that generates JSON in Hypermedia Application Language format.
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> {
}