使用Spring Boot thymeleaf:在前端的表格中显示图像和其他信息

问题描述

我创建了广告表,并在文件系统中插入了广告的详细信息和图像,并在数据库中插入了其他信息。图像的名称是每个条目的ID。现在,我必须使用百里香叶在表格中显示所有信息,但我无法做到这一点。请检查以下代码::-

  1. 模型类:
    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;
  1. 存储库接口:
@Repository
public interface AdvertisementRepository extends JpaRepository (Advertisement,Integer) {
    
}

  1. 接口存储服务:

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);
    
}

  1. 存储服务实现(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);
        }

    }


  1. 在Controller中尝试使用Index方法生成显示在百里香模板上的列表:


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

  1. 胸腺索引模板

                                     <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>
    

解决方法

您需要将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());
}