1

I have a problem with Spring Content. I'm building a car rental service. The user has a profile page with the cars he owns and some information about them including an image. Then he can add a car and should provide an image of it. I decided to use Spring Content JPA strategy with my HSQLDB database. So, I can access a car image by going to the link /data/{id}. But I can't figure out how to fetch that car image at some page. Should I add a field image to my Car entity or there is an existing solution in Spring Content? Also, the car will be shown on the rental page among the cars of other users.

Car content fields:

@ContentId
private String contentId;

@ContentLength
private Long contentLength = 0L;

// if you have rest endpoints
@MimeType
private String mimeType = "image/png";

CarImageStore:

@StoreRestResource(path = "data")
@Repository
public interface CarImageStore extends ContentStore<Car, UUID> {
}

CarUIController:

@Controller
@RequestMapping("/cars")
public class CarUIController {
    private final CarService service;
    private final CarImageStore store;

    public CarUIController(CarService service, CarImageStore store) {
        this.service = service;
        this.store = store;
    }

    @GetMapping
    public String getAll(Model model) {
        model.addAttribute("cars", service.getAll());
        return "cars";
    }

    @PostMapping
    public String create(Car car,
                         @RequestParam("file") MultipartFile file,
                         @AuthenticationPrincipal User authUser) {
        store.setContent(car, file.getResource());
        service.create(car, authUser.getId());
        return "redirect:/profile";
    }
}
Paul Warren
  • 2,411
  • 1
  • 15
  • 22
leonaugust
  • 186
  • 1
  • 4
  • 15

1 Answers1

1

Looks like you are on the right tracks.

You have defined your @ContentId to be of type String on your entity but UUID on your ContentStore. These should be the same, and when using Spring Content JPA should be of type String.

Assuming you are using Spring Content REST and it is enabled (i.e. you either depend on spring-content-rest-boot-starter or you imported org.springframework.content.rest.RestConfiguration) then all you should need to do at that point is include a regular image tag in your HTML:

<img src="/data/{id}"/>

When requesting the image the browser will send an image-based Accept header which should make the request match the StoreRestController.getContent handler method that serves the content. Care should be taken to avoid other handlers in your application from accidentally grabbing these requests.

Paul Warren
  • 2,411
  • 1
  • 15
  • 22