使用springboot-thymeleaf:在前端的表中显示图像和其他信息

j9per5c4  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(504)

我已经创建了广告表,并在文件系统中插入了广告的细节和图像以及数据库中的其他信息。图像的名称是每个条目的id。现在我必须使用thymeleaf显示表中的所有信息,但我不能这样做。请检查以下代码:--
型号等级:

private String advertisementDesc;

    @Column(name = "advertisement_no")
    private String advertisementNo;

    @Column(name = "publish_date")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @Temporal(TemporalType.DATE)
    private Date publishDate;

    @Column(name = "close_date")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @Temporal(TemporalType.DATE)
    private Date closeDate;

    @Column(name = "apply_multiple_post")
    private Boolean applyMultiplePost;

    @Column(name = "is_active")
    private Boolean isActive;

    @Column(name = "action_by")
    private long actionBy;

    @Column(name = "action_date")
    private Date actionDate;

    @Column(name = "action_by_ip", length = 19)
    private String actionByIp;

存储库接口:

@Repository
public interface AdvertisementRepository extends JpaRepository (Advertisement, Integer) {

}

接口存储服务:

public interface AdvertisementStorageService {

    void init();

    void store(MultipartFile file, Integer id);

    Stream<Path> loadAll();

    Path load(String filename);

    Resource loadAsResource(String filename);

    void deleteAll();

    Page < Advertisement > findPaginated(int pageNo, int pageSize);

}

存储服务实现(loadall方法)

@Override
    public Stream<Path> loadAll() {
        try {
            return Files.walk(this.rootLocation, 1)
                    .filter(path -> !path.equals(this.rootLocation))
                    .map(path -> this.rootLocation.relativize(path));
        } catch (IOException e) {
            throw new StorageException("Failed to read stored files", e);
        }

    }

在控制器中,尝试使用索引方法生成列表以在模板中显示:

@GetMapping("index/page/{pageNo}")
    public String findPaginated(@PathVariable(value = "pageNo") int pageNo, Model model) {
        int pageSize = 2;

        Page<Advertisement> page = advertisementStorageService.findPaginated(pageNo, pageSize);
        List<Advertisement> listAdvt = page.getContent();

        model.addAttribute("currentPage", pageNo);
        model.addAttribute("totalPages", page.getTotalPages());
        model.addAttribute("totalItems", page.getTotalElements());
        model.addAttribute("listAdvt", listAdvt);

        return "advertisement/index-advertisement";
    }

    @GetMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

        Resource file = advertisementStorageService.loadAsResource(filename);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
                .body(file);
    }
 @GetMapping("index")       // This is to show index page
            public String showAdvertisementIndex(Model model) {

             model.addAttribute("files", advertisementStorageService
                     .loadAll()
                     .map(path -> MvcUriComponentsBuilder.fromMethodName(AdvertisementController.class,
                        "serveFile", path.getFileName().toString()).build().toUri().toString())
                        .collect(Collectors.toList()));
             Iterable<Advertisement> data = advertisementRepository.findAll();

             model.addAttribute("advertisements", advertisementRepository.findAll());
             return findPaginated(1, model);  

//                  return "advertisement/index-advertisement";
        }

thymeleaf索引模板

<tr th:each="advertisement,iterator : ${advertisements}">
                                     <td th:text="${iterator.count}"></td>
                                     <td th:text="${advertisement.id}"></td>
                                     <td th:text="${advertisement.advertisementDesc}"></td>
                                     <td th:text="${advertisement.advertisementNo}"></td>
                                     <td th:text="${advertisement.publishDate}"></td>
                                     <td th:text="${advertisement.closeDate}"></td>
                                     <!--                                            <td th:text="${advertisement.advertisementFile}"></td> -->
                                     <td th:text="${advertisement.applyMultiplePost}"></td>
                                     <td th:text="${advertisement.isActive}"></td>
                                     <td><a
                                         th:href="@{/advertisement/edit/{id}(id=${advertisement.id})}"
                                         class="btn btn-success"> <i
                                             class="fas fa-user-edit ml-2"></i></a></td>
                                     <td><a
                                         th:href="@{/advertisement/delete/{id}(id=${advertisement.id})}"
                                         class="btn btn-success"> <i
                                             class="fas fa-user-times ml-2"></i></a></td>
                                     <td>document</td>
                                 </tr>
                                 <tr>
                                     <td th:text="${localDateTime}"></td>
                                 </tr>
                                 <tr th:each="file: ${files}">
                                     <td><a th:href="${file}" /> <img
                                         th:src="@{/img/pdf.png}" style="width: 50px; height: 60px;">

                                     </td>
                                     <td></td>
                                 </tr>
mwngjboj

mwngjboj1#

你需要加上 advertisements 列表到模型属性。
另一方面,对于下载文件,可以附加 InputStream 在回应中。

@GetMapping("/files/{filename:.+}")
public void serveFile(@PathVariable String filename, HttpServletResponse response) {

     // Load the inputStream
     // InputStream = ...

     // Attach in the response
     String contentType = new ConfigurableMimeFileTypeMap().getContentType(fileName);
     res.setContentType(contentType);
     res.addHeader("Content-Disposition", String.format("attachment;filename=\"%s\"", fileName));

     ByteStreams.copy(inputStream, res.getOutputStream());
}

相关问题