为什么无法使用百里香和Spring Boot在网页上显示图像?

时间:2020-09-10 13:51:09

标签: spring-boot thymeleaf

我想做的是显示使用百里香卡片通知从Mysql数据库获取的图像到网页。

但是不是通过传递url(http://localhost:8080/showapplication/v2)来获取卡片中的图像,而是在浏览器中得到的响应:-

enter image description here

我不知道我在做什么错。请帮助我实现所需的输出。

控制器类:-

@Controller
@RequestMapping("/showapplication")
public class ShowImageController {

    @Autowired
    private ImageRepository imageRepository;
    @Autowired
    private ImageService imageService;

    @GetMapping("/v2")
    public String ShowAllImages(Model model){
        List<ImageEntity> allImages=imageService.RetriveAllImages();
        model.addAttribute("listofimages",allImages);
        return "showimage";
    }
}

服务等级:-

@Service
public class ImageService {

    @Autowired
    private ImageRepository imageRepository;

    public void uploadtodb(MultipartFile file){

        ImageEntity imageEntity=new ImageEntity();
        try {
            imageEntity.setImage(file.getBytes());
            imageEntity.setFiletype(file.getContentType());
            imageEntity.setImagename(file.getOriginalFilename());
            imageRepository.save(imageEntity);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<ImageEntity> RetriveAllImages()
    {
        List<ImageEntity> imagesEntities;
        return imagesEntities=imageRepository.findAll();
    }
}

HTML代码:-

<!DOCTYPE html>
<html lang="en" xmlns:th="html://thymeleaf.org">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
      integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
      crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Aguafina Script' rel='stylesheet' >
<link href='https://fonts.googleapis.com/css?family=Alegreya SC' rel='stylesheet'>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>allimages</title>
</head>

<body>
<br>
<br>
<div class="container" >
    <div class="row">
        <div class="col-xl-3" th:each="allimages, istat : ${listofimages}">
            <div class="card" style="width: 15rem;">
                <img class="card-img-top" th:src="${allimages.image}" alt="Card image cap">
                <div class="card-body">
                    <p class="card-title" th:text = "${allimages.imagename}"></p>
                    <hr>
                    <p class="card-text" th:text = "${allimages.filetype}"></p>
                </div>
            </div>
            <span th:if="${istat.count % 4 == 0}"><br></span>
        </div>
    </div>
</div>
</body>
</html>

谢谢。 任何帮助将不胜感激..

1 个答案:

答案 0 :(得分:0)

将HTML更改为:

<img class="card-img-top" th:src="@{allimages.image}" alt="Card image cap">

请注意,在这种情况下,我们使用@而不是$中的<img th:src>。 有关更多详细信息,请参见此article