首页 > 解决方案 > Spring内容,如何在其他页面获取图片

问题描述

我对 Spring Content 有疑问。我正在建立汽车租赁服务。用户有一个个人资料页面,其中包含他拥有的汽车以及一些关于它们的信息,包括图像。然后他可以添加一辆车并且应该提供它的图像。我决定对我的 HSQLDB 数据库使用 Spring Content JPA 策略。因此,我可以通过链接 /data/{id} 访问汽车图像。但我不知道如何在某个页面上获取该汽车图像。我应该将字段图像添加到我的 Car 实体还是 Spring Content 中存在现有解决方案?此外,该汽车将显示在其他用户的汽车中的租赁页面上。

汽车内容字段:

@ContentId
private String contentId;

@ContentLength
private Long contentLength = 0L;

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

汽车图像商店:

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

汽车UI控制器:

@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";
    }
}

标签: imagespring-bootfileimage-processingspring-content-community-project

解决方案


看起来你在正确的轨道上。

您已经在您的实体上定义了您@ContentId的类型,但在您的 ContentStore 上。这些应该是相同的,并且在使用 Spring Content JPA 时应该是.StringUUIDString

假设您正在使用 Spring Content REST 并且它已启用(即您依赖spring-content-rest-boot-starter或导入org.springframework.content.rest.RestConfiguration),那么您此时需要做的就是在 HTML 中包含一个常规图像标签:

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

当请求图像时,浏览器将发送一个基于图像的 Accept 标头,该标头应该使请求与StoreRestController.getContent提供内容的处理程序方法相匹配。应注意避免应用程序中的其他处理程序意外抓取这些请求。


推荐阅读